blogger counters

Wednesday, March 17, 2010

Working with XDocument and Namespaces

I really like working with the new LINQ support for XML files. However, every time I work with a document that has namespaces, I stumble. For some reason, I just can’t remember all the details required to be able to use XPath expressions when you have namespaces defined in an XML file. A blog post, therefore, seems like a good idea.

Default Namespace

A common case is where an XML file has a default namespace defined at the very top. For example,

<Project ToolsVersion="3.5" DefaultTargets="Build" 
I wanted to retrieve the RootNamespace element, which without the default namespace can be done with code like this:
return doc.Root.XPathSelectElement("PropertyGroup/RootNamespace").Value
But when you have a default namespace, you’ll get an exception because the XPathSelectElement method returns null. Instead, you have to use a namespace manager like this:
XmlNamespaceManager namespaces = new XmlNamespaceManager(new NameTable());
XNamespace ns = _doc.Root.GetDefaultNamespace();
namespaces.AddNamespace("ns", ns.NamespaceName);
return doc.Root.XPathSelectElement("ns:PropertyGroup/ns:RootNamespace", namespaces).Value;
The trick, as you can see, is to give a name (“ns” in this example) to the default namespace, and then explicitly refer to that name in your XPath expression.


At 5/21/10, 2:11 AM, Anonymous Anonymous said...

Thank you! That helped solve my dilemma. I couldn't figure out the correct syntax originally to query the XElement that had a namespace - your solution worked.

At 2/12/11, 6:15 PM, Anonymous Anonymous said...

Excellent. If the parent node has a namespace then that applies to all the child elements under that element even if it is not explicitely specified. That is why we need to prefix it with the namespace.

At 2/6/15, 6:45 AM, Anonymous Anonymous said...

Thanks ... It worked exactly the way i wanted.

At 2/13/15, 10:40 AM, Blogger David Nelson said...


At 11/3/15, 12:15 PM, Blogger Raj Gohil said...

Thanks, this helped me.

At 11/3/15, 12:15 PM, Blogger Raj Gohil said...

Thanks lot, this helped me.


Post a Comment

Links to this post:

Create a Link

<< Home