How do I select nodes that use a default namespace?

谁说我不能喝 提交于 2019-11-26 23:44:16

问题


The structure of the XML file is more or less as follows:

<?xml version="1.0" encoding="UTF-8"?>
<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="url1" xsi:schemaLocation="url2 url3">
   <b>
     <c></c>
     <c></c>
     <c></c>
   </b>
</a>

My goal is to select all the "c" elements, but the following xpath expression won't work: "//a/b/c".

ie:

XmlDocument doc= new XmlDocument();
doc.Load(filepath);
XmlNodeList l = doc.SelectNodes("//a/b/c"); // 0 nodes

The only xpath expressions I tested that worked are /* (1 node) and //* (all nodes).

Is this problem related to the XML namespace? If so, what's the proper way to set up the XMLDocument object?

        XmlDocument doc= new XmlDocument();
        doc.Load(filepath);
        XmlNamespaceManager m = new XmlNamespaceManager(doc.NameTable);
        m.AddNamespace(/* what goes here? */);
        XmlNodeList l = doc.SelectNodes("//a/b/c", m);

回答1:


You need to assign a namespace prefix for the default namespace that the document is using, and then use that in your XPath:

XmlDocument doc= new XmlDocument();
doc.Load(filepath);

XmlNamespaceManager m = new XmlNamespaceManager(doc.NameTable);
m.AddNamespace("myns", "url1");

XmlNodeList l = doc.SelectNodes("/myns:a/myns:b/myns:c", m);

You can replace the prefix "myns" with essentially anything (alphanumeric without spaces), as long as it's consistent between line 4 and the XPath, and that it's correctly assigned to the "url1" namespace in line 4.



来源:https://stackoverflow.com/questions/14370989/how-do-i-select-nodes-that-use-a-default-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!