Rant: First off I find it extremely irritating when individuals use Namespaces in simple XML documents just for the heck of it! Just because you can use it doesn’t mean you should. Use Namespaces where appropriate, like when there are naming conflicts due to the use of multiple Schema’s on a single document. This is of course just my opinion so take it or leave it!
One issue I have run across on multiple occasions when parsing XML documents with multiple Namespaces (or even a single Namespace) using XPath is the fact that XPath is designed to select nodes that are not within a Namespace or within a specific Namespace. for some reason I always just assume the XPath expression “//customer” will pull out all customer elements in a document no matter where in the document they are located.
Code Example: { XmlNodeList selected = Customers.SelectNodes("//customer");}
This is true, if and only if your document does not have any Namespaces defined or all of your customer elements are outside of any defined Namespaces. But if your document contains a Namespace and those customer elements are inside it the code will simply return a big fat null.
In order to overcome Namespace issues you have to use the XmlNamespaceManager class which is passed along with your XPath query. Not only do you need to pass the manager with the XPath you now have to modify the query to use the Namespace prefix you assigned when instantiating the manager.
Code Example:{ XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); manager.AddNamespace("c", "MyCustomerNamespace"); XmlNodeList selected = Customers.SelectNodes("//c:customer", manager);}
Now you will retrieve all of the customer elements in the XML document because now you have specified that instead of searching all nodes without a Namespace it should search all nodes within the “MyCustomerNamespace” Namespace.
Published by