Parsing an XML document using XPath, C #

So, I am trying to parse the following XML document using 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> 

In every XPath treaty with namespaces, I need 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 request

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

It works fine, but returns nothing. Following:

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

returns two nodes if I modify the XML file and delete the namespaces, so everything else seems to be configured correctly. Any idea why this works, not with namespaces?

Thanks a lot!

+4
c # xml xpath
source share
3 answers

As indicated, this namespace URI is important, not a prefix.

Given your xml, you can 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 need. Once you understand this concept, it will become easier for you, especially when you fall into the default namespace (without a prefix in the original xml), since you immediately know that you can assign a prefix to each URI and strongly refer to any part of the document which you like.

+6
source share

The URI you specify in the AddNamespace method does not match that in the xmlns declaration.

+2
source share

If you declare the prefix "n" to represent the namespace " http://www.w3.org/1999/XSL/Transform ", then the nodes will not match when you make your request. This is because in your document, the prefix "n" refers to the namespace " http://www.w3.org/TR/html4/ ".

Try to do mgr.AddNamespace("n", "http://www.w3.org/TR/html4/"); instead of this.

+1
source share

All Articles