Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing XML document with XPath, C#

Tags:

c#

xml

xpath

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!

like image 802
Vercinegetorix Avatar asked Dec 30 '22 16:12

Vercinegetorix


2 Answers

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.

like image 106
Timothy Walters Avatar answered Jan 01 '23 04:01

Timothy Walters


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

like image 41
Steven Sudit Avatar answered Jan 01 '23 06:01

Steven Sudit