【问题标题】:c# XmlDocument SelectNodes isn't returning nodesc# XmlDocument SelectNodes 不返回节点
【发布时间】:2015-06-07 06:36:08
【问题描述】:

我正在尝试创建一个通用的 XmlParsing 方法。以 Xml 为例:

<body>
<section>
    <subsection1>
        ...
    </subsection1>
    <subsection2>
        ...
    </subsection2>
</section>
<section>
    <subsection1>
        ...
    </subsection1>
    <subsection2>
        ...
    </subsection2>
</section>
</body>

我试图在不知道它们有多深或它们的父节点名称的情况下抓取所有“节”节点。

到目前为止我有(我的 XML 是字符串格式)

        XmlDocument xml = new XmlDocument();
        xml.LoadXml(XMLtoRead);

        XmlNodeList nodes = xml.DocumentElement.SelectNodes("//section");

但是节点数始终为 0。我的印象是“//”前缀递归地在文档中搜索命名的节点。

我真正的 XML 是一个 SOAP 回复:

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">


<soap:Body>
    <Response xmlns="http://tempuri.org/">

【问题讨论】:

  • 您的 xml 文档中是否有命名空间 URL?
  • 是的,我的 xml 文档的顶级元素中有许多 url。 xmlns="一些网址"。
  • 我的 XML 是 SOAP 回复,请参阅问题编辑

标签: c# xpath xmldocument selectnodes


【解决方案1】:

在这种情况下,它不是通用的,而是特定于您的 SOAP 回复类型。 ;-) 试试这个:

var ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("ns", "http://tempuri.org/");
XmlNodeList nodes = xml.DocumentElement.SelectNodes("//ns:section", ns);

【讨论】:

  • 找了2个小时,终于找到了。谢谢。甚至不知道这个愚蠢的名称空间对 XML 文档有这么大的影响...
猜你喜欢
  • 2013-05-29
  • 2017-05-01
  • 2017-02-19
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
相关资源
最近更新 更多