[英]How to select particular level node from xmldocument
XmlDocument is looks as below, want to select the one node that is under <soap:Body>
XmlDocument如下所示,要选择<soap:Body>
下的一个节点
so, any first node under path: soap:Envelope/soap:Body/
so, at below example, need to select "DynamicNode" element (But, It should not be through "DynamicNode" as it can be any name under soap:Envelope/soap:Body/
因此, path: soap:Envelope/soap:Body/
下的任何第一个节点path: soap:Envelope/soap:Body/
因此,在下面的示例中,需要选择“ DynamicNode”元素(但是,不应通过“ DynamicNode”,因为它可以是soap:Envelope/soap:Body/
下的任何名称soap:Envelope/soap:Body/
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
</soap:Header>
<soap:Body>
<DynamicNode> ....</DynamicNode>
</soap:Body>
</soap:Envelope>
Tried with, doc.DocumentElement.SelectSingleNode("soap:Envelope/soap:Body/") but it did not work and throw exception. 尝试使用doc.DocumentElement.SelectSingleNode(“ soap:Envelope / soap:Body /”),但它不起作用并引发异常。
Note: can not use Linq.Xml 注意:不能使用Linq.Xml
Because xml contains namespaces, you must use the XmlNamespaceManager. 由于xml包含名称空间,因此必须使用XmlNamespaceManager。
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
XmlNode body = doc.SelectSingleNode("//soap:Body", manager);
XmlNode first = body.FirstChild; // DynamicNode
If xml has the xml:space="preserve"
attribute, the above code can return a whitespace node. 如果xml具有xml:space="preserve"
属性,则上述代码可以返回空白节点。
I can offer the following: 我可以提供以下内容:
XmlNode first = doc.SelectSingleNode("//soap:Body/*[text()]", manager);
This will return the first non-empty element. 这将返回第一个非空元素。
XmlDocument doc = new XmlDocument();
doc.LoadXml(...);
XmlNode target;
XmlNode root = doc.FirstChild;
for (int i = 0; i < root.ChildNodes.Count; i++)
{
if (root.ChildNodes[i].Name == "soap:Body")
{
target = root.ChildNodes[i].ChildNodes[0];
}
}
Not elegant, but target
will contain the first child node of "soap:Body" 不够优雅,但target
将包含“ soap:Body”的第一个子节点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.