【问题标题】:XPATH returns null for XML with namespaceXPATH 为具有命名空间的 XML 返回 null
【发布时间】:2012-07-27 05:54:40
【问题描述】:

我有以下 XML。

<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://localhost/gsainis/GsaInisWebService">
    <string>
        <gsafeed>
            <group action="add">
                <record>
                 ......
                 ......
                </record>
            </group>
        </gsafeed>
   </string>
</ArrayOfString>

我正在使用 C# 代码 (.NET 4.0) 来解析这个 XML。我正在使用下面的代码来选择上述 XML 中的所有 &lt;record&gt; 节点。

XmlNamespaceManager xmlnsmgr = new XmlNamespaceManager(INISRecordXMLdoc.NameTable);
xmlnsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlnsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
xmlnsmgr.AddNamespace(string.Empty, "http://localhost/gsainis/GsaInisWebService");

foreach (XmlNode node in INISRecordXMLdoc.SelectNodes("//ArrayOfString/string/gsafeed/group/record",xmlnsmgr))
{
    //Do something
}

问题是永远不会执行 foreach 循环。应该使用什么正确的 XPath 才能获得所有 &lt;record&gt; 节点?

【问题讨论】:

    标签: c# asp.net xml xpath


    【解决方案1】:

    试试这个 - 我过去曾遇到过使用“空”XML 前缀的问题:

    XmlNamespaceManager xmlnsmgr = new XmlNamespaceManager(INISRecordXMLdoc.NameTable);
    xmlnsmgr.AddNamespace("ns", "http://localhost/gsainis/GsaInisWebService");
    
    foreach (XmlNode node in INISRecordXMLdoc.SelectNodes("//ns:ArrayOfString/ns:string/ns:gsafeed/ns:group/ns:record", xmlnsmgr))
    {
       // Do something
    }
    

    使用空字符串以外的其他内容 - 并在 XPath 中使用 XML 命名空间前缀。

    【讨论】:

    • 两天前我读到了 XmlNamespaceManager。现在在这里。现在我只需要我自己使用它,我将来使用它会很自然:)
    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 2010-10-08
    • 2020-06-08
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多