Using XPath with a default namespace in .NET 2.0

I have recently been writing an assembly which facilitates automatic deployment of K2.Net 2003 workflows. The assembly reads in a configuration file and deploys the workflows as specified in the configuration file. Also, rather than writing any custom code to validate the XML, I decided to use an XML Schema Definition, mainly because it saves me time and typing, but also because it’s good practice.

Anyhow, in order to use the XSD, I had to give my schema a namespace, and because I didn’t want to have to add a whole bunch of prefixes to my configuration file, I decided to use the default namespace:

<configuration xmlns=""></configuration>

This broke all my xpath queries because the .NET XPath query code does not seem to handle the default namespace. What I ended up doing to fix it was using an XmlNamespaceManager to create a fake namespace with the same URI as the default namespace, and then change all of my XPath queries to use the prefix for that fake namespace. Something like:

XmlDocument doc = new XmlDocument();
// To get the URI for the default namespace
string xmlns = doc.DocumentElement.GetAttribute("xmlns");
XmlNamespaceManager namespaceManager = new XmlNamespaceManager();
namespaceManager.AddNamespace( "a", xmlns );

// Now query with XPath
XmlNodeList nodes = doc.SelectNodes("/a:configuration/a:solution");

With a configuration file which looks something like:

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns="" ... >
	<solution path="">
			<project name="Job Setup">
					<reference name="" gac="false" fullname="" />
					<process name="RequestLeave" />
					<process name="RequestSomethingElse" />

The way I see it, it involves less typing than actually using a prefix. That said, given that it feels like a lazy way out, it probably isn’t the best practice because there is now a difference between my queries and my xml.

2 thoughts on “Using XPath with a default namespace in .NET 2.0

Leave a Reply

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

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.