4

So I'm trying to parse the following XML document with C#, using System.XML:

<root xmlns:n="http://www.w3.org/TR/html4/">
 <n:node>
  <n:node>
   data
  </n:node>
 </n:node>
 <n:node>
  <n:node>
   data
  </n:node>
 </n:node>
</root>

Every treatise of XPath with namespaces tells me to do the following:

XmlNamespaceManager mgr = new XmlNamespaceManager(xmlDoc.NameTable);
mgr.AddNamespace("n", "http://www.w3.org/1999/XSL/Transform");

And after I add the code above, the query

xmlDoc.SelectNodes("/root/n:node", mgr);

Runs fine, but returns nothing. The following:

xmlDoc.SelectNodes("/root/node", mgr);

returns two nodes if I modify the XML file and remove the namespaces, so it seems everything else is set up correctly. Any idea why it work doesn't with namespaces?

Thanks alot!

  • This answer might also help: http://stackoverflow.com/questions/4191084/linq-to-xml-problem-with-colon-in-the-xml-tags/8862051#8862051 – Nick Josevski Jan 14 '12 at 11:56

3 Answers3

7

As stated, it's the URI of the namespace that's important, not the prefix.

Given your xml you could use the following:

mgr.AddNamespace( "someOtherPrefix", "http://www.w3.org/TR/html4/" );
var nodes = xmlDoc.SelectNodes( "/root/someOtherPrefix:node", mgr );

This will give you the data you want. Once you grasp this concept it becomes easier, especially when you get to default namespaces (no prefix in source xml), since you instantly know you can assign a prefix to each URI and strongly reference any part of the document you like.

Timothy Walters
  • 16,866
  • 2
  • 41
  • 49
2

The URI you specified in your AddNamespace method doesn't match the one in the xmlns declaration.

Steven Sudit
  • 19,391
  • 1
  • 51
  • 53
1

If you declare prefix "n" to represent the namespace "http://www.w3.org/1999/XSL/Transform", then the nodes won't match when you do your query. This is because, in your document, the prefix "n" refers to the namespace "http://www.w3.org/TR/html4/".

Try doing mgr.AddNamespace("n", "http://www.w3.org/TR/html4/"); instead.

Nader Shirazie
  • 10,736
  • 2
  • 37
  • 43