XPath, XML and Namespaces

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

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Connecting to %s