XPath & Namespaces

I'm sure many out there know this or figured it out eons ago, but it was new to me and took awhile to figure out.

Say you have a RDF style XML document that looks something like:

<?xml version="1.0" encoding="iso-8859-1" ?>
<
rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns
="http://purl.org/rss/1.0/">
<
channel rdf:about
="http://someplace.com/weblog/">
<
title>
News from Bob</title>
<
link>http:// someplace.com/weblog/</link
>
<
description></description
>
<
dc:language>en-us</dc:language
>
<
dc:creator>Bob</dc:creator
>
<
dc:rights>Copyright 2003 Bob</dc:rights
>
<
dc:date>2003-03-19T22:30:34-07:00</dc:date
>
<
admin:generatorAgent rdf:resource="http://www.movabletype.org/?v=2.51"
/>
<
admin:errorReportsTo rdf:resource="mailto:tbob@somewhere.com"
/>
<
sy:updatePeriod>hourly</sy:updatePeriod
>
<
sy:updateFrequency>1</sy:updateFrequency
>
</
channel
>
<
item rdf:about
="http://somewhere/weblog/archives/2003/03/19.shtml#how_i_really_feel_about_cheese">
<
title>How I really feel about Cheese</title
>
<
description>&lt;p
&gt;
I was asked in a comment why I really don't like cheese...</description>
</item>
</rdf:RDF>

Simplistically I thought the following code would work:

XmlNode dateNode = rdfXml.SelectSingleNode("/RDF/channel/date");

But of course it returns Null. So I tried the following:

XmlNode dateNode = rdfXml.SelectSingleNode("/rdf:RDF/channel/dc:date");

 

Of course this returned Null as well. So it was time to turn to the help file, which didn’t help much. My next best friend is Google, and Google Groups didn’t let me down. Turns out SelectSingleNode is overloaded and takes a XmlNamespaceManager as the second parameter. I now had this:

 

nsMgr = new XmlNamespaceManager(rdfXml.NameTable);

nsMgr.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");

nsMgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");

 

XmlNode dateNode = rdfXml.SelectSingleNode("/rdf:RDF/channel/dc:date", nsMgr);

 

However, I didn’t know what to do with the default namespace. A little more research lead me to the nugget that there is no such thing as a default namespace in XPath, so all I has to do was add the default namespace with the prefix of my choosing.

 

nsMgr = new XmlNamespaceManager(feedXml.NameTable);

nsMgr.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");

nsMgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");

nsMgr.AddNamespace("rss", "http://purl.org/rss/1.0/");

 

XmlNode dateNode = rdfXml.SelectSingleNode("/rdf:RDF/rss:channel/dc:date", nsMgr);

 

Now everything works like it should.

 

Full example (.Net 2.0):

 

using System.Xml;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument rdfXml = new XmlDocument();
            rdfXml.Load("data.xml");
            XmlNamespaceManager nsMgr = new XmlNamespaceManager(rdfXml.NameTable);
            nsMgr.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
            nsMgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
            nsMgr.AddNamespace("rss", "http://purl.org/rss/1.0/");

            XmlNode dateNode = rdfXml.SelectSingleNode("/rdf:RDF/rss:channel/dc:date", nsMgr);
        }
    }
}

Published Wednesday, April 02, 2003 7:01 PM by Wayne Allen
Filed under: , ,

Comments

# re: XPath & Namespaces

Thank you. I find this very userful.

Monday, March 29, 2004 10:28 AM by David

# Xml Schema Validation and XPath Query

Wednesday, April 14, 2004 2:03 PM by TrackBack

# re: XPath & Namespaces

Just what I needed... thanks very much!

Thursday, June 10, 2004 5:31 AM by Dave

# re: XPath & Namespaces

Thank you.

Friday, July 23, 2004 4:42 AM by Alberto

# re: XPath & Namespaces

YES!!! Thank you very much!

Tuesday, June 13, 2006 6:43 AM by PJ

# re: XPath & Namespaces

Adds the given namespace to the collection.

[Visual Basic]

Public Overridable Sub AddNamespace( _

  ByVal prefix As String, _

  ByVal uri As String _

)

[C#]

public virtual void AddNamespace(

  string prefix,

  string uri

);

Parameters

prefix:

The prefix to associate with the namespace being added. Use String.Empty to add a default namespace.

However, if the XmlNamespaceManager will be used for resolving namespaces in an XPath expression, a prefix must be specified. If an XPath expression does not include a prefix, it is assumed that the namespace URI is the empty namespace. For more information about XPath expressions and the XmlNamespaceManager, refer to the XmlNode.SelectNodes and XPathExpression.SetContext methods.

uri:

The namespace to add.

Monday, July 31, 2006 2:30 PM by Kiran Gudupalli

# re: XPath & Namespaces

Thank you very much. This is really help full.

Use String.Empty as First paramenter in AddNamespace method to add a default namespace.

Monday, July 31, 2006 2:32 PM by Kiran Gudupalli

# re: XPath & Namespaces

wow, thx. that really helped.

Wednesday, September 06, 2006 5:56 AM by Joern

# re: XPath & Namespaces

Exactly what I needed.  Thanks so much

Wednesday, December 20, 2006 9:42 PM by Nathan Rose

# re: XPath & Namespaces

thanks, really helped.

Thursday, March 29, 2007 3:07 PM by Clint

# re: XPath & Namespaces

Known bug, using String.Empty does not work to set a default namespace.

See the following:

connect.microsoft.com/.../ViewFeedback.aspx

Tuesday, May 22, 2007 6:20 PM by moecazzell

# re: XPath & Namespaces

Thanks!! I had exactly the same issue with the default namespace, and the MS documentation suggests using string.empty for the prefix. Your tip did the trick!

Monday, June 11, 2007 10:16 AM by paknet

# re: XPath & Namespaces

Thanks!!!  Nice, simple explanation - exactly what I was looking for.

Thursday, September 13, 2007 1:33 PM by Tanya Z

# re: XPath & Namespaces

Thanks a lot for sharing this.

Proved very useful.

Sheron

Thursday, September 20, 2007 12:18 AM by Sheron

# re: XPath & Namespaces

Thanks for sharing!  Google is also my best friend.  Cheers!

Monday, October 22, 2007 5:29 AM by Ramir Borja

# re: XPath & Namespaces

Phew, I finally solved a problem I'd been stuck on all morning with this nugget!

Tuesday, October 23, 2007 9:14 AM by Cornetto

# re: XPath & Namespaces

Excellent - Google now links directly to this so I didn't have to search as much as you all those years ago!

Tuesday, November 13, 2007 7:44 AM by Robin Massart

# re: XPath & Namespaces

Excellent!! Thanks alot...

This is exactly what I wanted & it has become my one stop look up for XPath isssue..

Thank you...

Wednesday, December 05, 2007 4:50 AM by Sandeep

# re: XPath & Namespaces

Great artilce it saved me a lot of time :)))

Wednesday, February 20, 2008 11:36 AM by Lukas F

# re: XPath & Namespaces

Thanks, it really helps.

Wednesday, March 12, 2008 6:23 AM by Bruce Li

# re: XPath & Namespaces

Awesome, really clear.  I was scatching my head over this one.  Thanks for sharing.

Monday, March 17, 2008 9:58 AM by Bob Smith

# Пространства имен в XML c привлечением .NET

Pingback from  Пространства имен в XML c привлечением .NET

# re: XPath & Namespaces

All woking like a dream! Thanks for that.

Monday, April 21, 2008 9:21 AM by Phil

# .NET: Using Namespaces with XPath in .NET

A colleague has been asking how to do this and I've found a great post written years ago. I've linked it here...

Friday, May 23, 2008 3:39 AM by Stephen Horsfield's Blog

# re: XPath & Namespaces

I try that code but why it shows an error?

nsMgr = new XmlNamespaceManager(feedXml.NameTable);

nsMgr.AddNamespace("rdf", "www.w3.org/.../22-rdf-syntax-ns);

nsMgr.AddNamespace("doc", "localhost/.../");

XmlNode dateNode = rdfXml.SelectSingleNode("/rdf:RDF/rdf:Description", nsMgr);

Here is my RDF file:

<?xml version="1.0" encoding="ISO-8859-1"?>

<rdf:RDF xmlns:rdf="www.w3.org/.../22-rdf-syntax-ns xmlns:doc="localhost/.../">

<rdf:Description rdf:about="localhost/.../Policy2.pdf>

<doc:desc_id>048/26/SMD/HRD/9/00</doc:desc_id>

<doc:title>Kebijakan2</doc:title>

<doc:dates>3/21/1999</doc:dates>

<doc:author>Smart Co</doc:author>

<doc:file_name>Policy2</doc:file_name>

<doc:type>pdf</doc:type>

<doc:category>memorandum</doc:category>

<doc:status>tidak_berlaku</doc:status>

<doc:year>1983</doc:year>

<doc:keyword></doc:keyword>

</rdf:Description>

</rdf:RDF>

Thanks

Tuesday, June 17, 2008 7:20 AM by deean

# Darren Hobbs &raquo; Blog Archive &raquo; JDom, XPath and the saga of the invisible namespace

Pingback from  Darren Hobbs  &raquo; Blog Archive   &raquo; JDom, XPath and the saga of the invisible namespace

# re: XPath & Namespaces

LOL..Cant believe I am one of the so many with the same issue....Thanks for the great info nugget

Tuesday, December 30, 2008 3:25 PM by PSK

# Default Namespace and XPath in VB.NET

Pingback from  Default Namespace and XPath in VB.NET

Friday, January 09, 2009 5:10 AM by Default Namespace and XPath in VB.NET

# re: XPath & Namespaces

Thanks for the update. Somewhat surprised this isn't documented, very helpfull.

Monday, January 12, 2009 5:18 AM by Karlo

# re: XPath & Namespaces

Awesome - sorted my problem in a minute,

Cheers!

Thursday, February 05, 2009 4:55 AM by Mike

# Using XPath to select nodes with namespace in C# / 在C#中用XPath選取具有namespace之節點

Pingback from  Using XPath to select nodes with namespace in C# / 在C#中用XPath選取具有namespace之節點 | Phanix's Blog

# re: XPath & Namespaces

it looks great..

but will it work with selectNodes? im tryin to access gml data from geoserver`s wfs service..

the DOM object is created well..

but when i try to select nodes according to schema doing the following:

var xmlDOM = xmlhttp.responseXML; // geting DOM through URL

//alert(xmlDOM);

var tasNodes = xmlDOM.selectNodes('/wfs:FeatureCollection/gml:featureMembers/topp:tasmania_water_bodies');

-----------------

the error i get is tht wfs is undeclared namespace..

Tuesday, June 23, 2009 3:45 PM by Imran

# re: XPath & Namespaces

Imran,

You still need to create a namespace manager with the appropriate uri.

var xmlDOM = xmlhttp.responseXML;

var nsMgr = new XmlNamespaceManager(xmlDOM.NameTable);

nsMgr.AddNamespace("wfs", "http://correct.uri");

var tasNodes = xmlDOM.selectNodes('/wfs:FeatureCollection/gml:featureMembers/topp:tasmania_water_bodies', nsMgr );

Tuesday, June 23, 2009 5:50 PM by Wayne Allen

# re: XPath & Namespaces

duh!! now it doesnt recognize XmlNamespaceManager

XmlNamespaceManager undefined!!!

maaaan this is so annoying :(

Wednesday, August 12, 2009 1:15 AM by Imran

# re: XPath & Namespaces

Imran,

If you can supply more information I could help more.

Wednesday, August 12, 2009 6:44 PM by Wayne Allen

# re: XPath & Namespaces

Awesome, thanks for sharing. Exactly what i wanted

Tuesday, October 06, 2009 9:04 PM by Ravi Yellasiri

# re: XPath & Namespaces

awesome, thanks a lot

Tuesday, November 17, 2009 1:03 AM by maingi4

# re: XPath & Namespaces

Thanks! helped a lot

Friday, December 04, 2009 3:13 AM by Stefan Gustafsson

# re: XPath & Namespaces

Sorry my problem!

Tuesday, December 29, 2009 11:08 AM by Zhen

# re: XPath & Namespaces

Hi Guys, I see some of you are Pro.

In my case i am new to this and don't where to put this code:

nsMgr = new XmlNamespaceManager(feedXml.NameTable);

nsMgr.AddNamespace("rdf", "www.w3.org/.../22-rdf-syntax-ns);

nsMgr.AddNamespace("dc", "purl.org/.../");

XmlNode dateNode = rdfXml.SelectSingleNode("/rdf:RDF/channel/dc:date", nsMgr);  

I know in my case would look a little bit different but i believe, something is missing here.  Please try to be more specific.  

PS: Do i have to write the code in the "code behind" - page?

Thank you !

Friday, April 23, 2010 8:44 PM by niachipal

# re: XPath & Namespaces

niachipal -

Yes this would go in your code-behind for an aspx page as part of loading and parsing an XML document with namespaces. I.e. <dc:creator>Bob</dc:creator>, the "dc" part is an XML namespace. See: en.wikipedia.org/.../XML_namespace

Friday, April 30, 2010 12:26 PM by Wayne Allen

# re: XPath & Namespaces

Why the heck is this not documented!

Brilliant and thanks

Sunday, July 11, 2010 6:33 AM by Mark S

# re: XPath & Namespaces

Hey Wayne, thanks for this article. It really helps me with the namespace.

Friday, August 20, 2010 2:36 AM by Newb

# re: XPath & Namespaces

Thanks! A co-worker was having a similar problem with some XML and I was able to fix it by clearing the namespace.

Tuesday, October 05, 2010 7:17 AM by Andrew

# re: XPath & Namespaces

Work fine..This is Good article and very rare..

Thursday, December 02, 2010 6:29 AM by hsiva

# re: XPath & Namespaces

Thanks!, in 2011 this article is still update date!

Tuesday, March 22, 2011 10:50 AM by Bas

# re: XPath & Namespaces

4725.. Tiptop :)

Wednesday, April 06, 2011 12:13 AM by weblogs.asp.net

# re: XPath & Namespaces

Thanks, especially for the bit about handling the "default" namespace.

Monday, July 25, 2011 3:44 PM by Phil

# re: XPath & Namespaces

nsMgr = new XmlNamespaceManager(feedXml.NameTable);

what is feedXml ?

Friday, August 19, 2011 2:59 AM by Wesley isaac

# re: XPath & Namespaces

@Wesley - Whoops, after all these years you are the fist to catch this. It should have been rdfXml - fixed.

Friday, August 19, 2011 11:47 AM by Wayne Allen

# re: XPath & Namespaces

This should be the first search result when looking for reading from Default Name Spaces. This solved my issues with the so called default name spaces thanks!

Monday, September 05, 2011 6:55 AM by Alex

# re: XPath & Namespaces

T H A N K S !

Monday, October 17, 2011 11:07 PM by KJ

# re: XPath & Namespaces

thanks

Monday, November 28, 2011 4:39 AM by doanh

# re: XPath & Namespaces

I appreciate your so much, can't describe how much time it took me to figure out "Default Namespace"

Thursday, December 08, 2011 8:38 PM by Karthik

# re: XPath & Namespaces

Thanks.

And yeah, whoever designed XML/namespaces/xpath this way should be shot

Monday, February 06, 2012 11:24 AM by MH

# re: XPath & Namespaces

thanks, it's solved my problem....

Thursday, February 16, 2012 8:55 AM by bhagya

# re: XPath & Namespaces

thanks, i used it for rubys libxml

Thursday, April 19, 2012 4:28 AM by Uwe

# The ADO.NET Entity Framework and SQL Server 2000: the ProviderManifestToken attribute and selecting it with XPath &laquo; The Wiert Corner &#8211; irregular stream of Wiert stuff

Pingback from  The ADO.NET Entity Framework and SQL Server 2000: the ProviderManifestToken attribute and selecting it with XPath &laquo; The Wiert Corner &#8211; irregular stream of Wiert stuff

# re: XPath & Namespaces

Thanks a lot!

Wednesday, July 18, 2012 10:00 AM by K

# re: XPath & Namespaces

Thanks for this, it helped a lot!

Wednesday, August 22, 2012 9:34 PM by OBrady

# re: XPath & Namespaces

Thanks, very useful!

Thursday, September 27, 2012 7:06 AM by DR

# re: XPath & Namespaces

Exactly what I was looking for. Thanks a lot.

Tuesday, October 02, 2012 2:00 PM by ruperth

# re: XPath & Namespaces

This was exactly what I needed. I loved your explanations and code.Thank you!

Tuesday, February 05, 2013 4:46 PM by Anna

Leave a Comment

(required) 
(required) 
(optional)
(required)