Carl’s Geek Notes

August 27, 2008

XmlNamespaceManager and overridden default XML namespace

Filed under: C#/.NET, Computers, Programming, Web Services, XML — Carl @ 12:22 pm

Issue: My XmlDocument.SelectNodes() or SelectSingleNode() wasn’t working correctly with the incoming XML. It was always returning null even when the element was specified.

Problem: If the XML has an overridden default XML namespace (i.e., the root node has an attribute xmlns=”urn:MyNamespace” in it), SelectNode is unable to properly resolve it.

Solution: Use an XmlNamespaceManager to give a prefix to the default namespace, like so:

string MyXML = "<?xml version=\"1.0\"?><MyElement xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"urn:MyNamespace\"><MySubElement>3</MySubElement></MyElement>";

// Create and load the XML document
XmlDocument MyDoc = new XmlDocument();
MyDoc.LoadXml(Response);

// Create a namespace manager with the XML document's name table
XmlNamespaceManager MyNamespaces = new XmlNamespaceManager(MyDoc.NameTable);

// Add namespaces for all prefixed xmlns declarations
MyNamespaces.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
MyNamespaces.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");

// Add the default namespace with a custom prefix
MyNamespaces.AddNamespace("MyNS", "urn:MyNamespace");

// Use the namespace manager to select the node
// Make sure that each element in the default namespace is prefixed with your custom prefix
// It is not sufficient to do MyNS:MyElement/MySubElement, both must be qualified!
XmlNode MyNode = MyDoc.SelectSingleNode("MyNS:MyElement/MyNS:MySubElement", MyNamespaces);

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.