3

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);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
John Smith
  • 4,416
  • 7
  • 41
  • 56

1 Answers1

9

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.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • 3
    Is it just me or any time we have to deal with namespaces, API feels like a rock? I mean it is a default namespace.... and adding namespaces is mandatory to those tags. Silly. I get that xml may contain namespaces and non-namespaced parts. At least they could have allowed `SelectNodes("/:a/:b/:c")`, but no... – Janis Veinbergs Jul 02 '21 at 13:18
  • @Janis Veinbergs. No it's not just you. Everybody hates those silly namespaces. It will makes so much more sense to precise namespaces ONLY when then matter (= 5% of time) – frenchone Feb 15 '23 at 15:20