Monday, March 26, 2007

SelectSingleNode with a default namespace

Ok, I have a simple xml file with a default namespace as shown here:

< test xmlns="">
< config>
< data>test< /data>
< settings>
< moredata>test< /moredata>
< /settings>
< /config>
< /test>

I loaded the xml file using
XmlTextReader reader = new XmlTextReader("C:\\xml\\My.Config.xml" );
nsm = new XmlNamespaceManager(reader.NameTable);

//I read that this is how you specify a default namespace
nsm.AddNamespace("", "");


and then I do a SelectSingleNode
XmlNode test2 = configDoc.SelectSingleNode("//Config");

This should work right? Wrong!!!
It turns out that XPath 1.0 doesn't support default namespace. XPath 2.0 does but I guess that doesn't help right now with .net 2.0.

What I needed to do was give the default namespace a name
nsm.AddNamespace("cfg", "");

Then all my selects need to specify this namespace
XmlNode test2 = configDoc.SelectSingleNode("//cfg:Config");

What a pain.


levin said...

and if you want to select a long explicit path like


you have to select it as


I don't see documentation or examples, but that's all that's working for me.

Anonymous said...

Thank you so much for this code - I was struggling with namespaces and this post helped me a ton!

Anonymous said...

I'm glad I'm not alone in thinking this is a pain! The W3C must be smoking crack!