John Smith John Smith - 2 months ago 17
C# Question

How do I select nodes that use a default namespace?

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);

Answer

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.