« View -> Tab Order | Main | Empty array in Oracle and .NET »

October 06, 2005

XPath and default namespace in .NET

I've been having a problem with running XPath query on XML document with a default namespace. It has something to do with NamespaceManager and prefixing all your XPath with the prefix that you set in the NamespaceManager. For example, if you have XML document as follow:


<MyXml xmlns="http://tempuri.org/myxml">
<name>Victor Hadianto</name>
</MyXml>

When you run a simple XPath such as /MyXml/name it will fail. Why? Because of the default namespace, .NET doesn't seem to know that if you don't prefix your query just use the default namespace. For example:


XmlNode node = xmlDoc.SelectSingleNode(@"/MyXml/name");
// node is null

The way to fix this is as follow:


// First create the NamespaceManager
XmlNamespaceManager nm = new XmlNamespaceManager(xmlDoc.NameTable);
// You have to create a prefix with the same URI as your default xmlns
nm.AddNamespace("bc", "http://tempuri.org/myxml");
// Now you can run the query
XmlNode node = xmlDoc.SelectSingleNode(@"/MyXml/name", nm);
// node won't be null here

Posted by vhadiant at October 6, 2005 06:07 PM





Trackback Pings

TrackBack URL for this entry:
http://www.hadianto.net/mov32/mt-tb.cgi/120

Comments

Post a comment





Remember Me?

(you may use HTML tags for style)