XML SelectSingleNode or SelectNodes and dealing with namespaces the easy way

Hi Folks,

Sometimes namespaces can be a real pain. Especially when child elements in an XML document have multiple namespaces etc.

Imagine a document like this:

<Root xmlns="http://www.example.com">

<Child xmlns="http://www.romiko.com/>
<Child xmlns="http://www.romiko.com/>

</Root>

 

To select the data  for all childs you have two ways to do it:

ns.AddNamespace("ro", "http://www.example.com");
ns.AddNamespace("ch", "http://www.romiko.com");
XmlNodeList nodes = doc.SelectNodes("/ro:Root/ch:Child", ns);

OR

XmlNodeList nodes = doc.SelectNodes("/*[local-name()=’Root’]/*[local-name()=’Child]");

As You can see I prefer the latter, less code and is XPATH compliant.

Advertisement
  • Uncategorized

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s