How Namespaces Can Hose Your XPath Queries in C#

Album Cover: Kid A

"We got heads on sticks. You got ventriloquists."
Radiohead / Kid A

Posted on January 21, 2009 3:49 PM in XML
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

I was working on a C# project today when I encountered a frustrating problem with some XPath queries. I was doing something along the lines of the following:

...
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator iter = null;

string query = "Level1/Level2";
iter = nav.Select(query);
string level2text = (iter.MoveNext()) ? iter.Current.Value : "";

After loading an XML document, I was performing an XPath query against the document to try and store the text content of the Level2 child of the Level1 node in a string called level2text.

I knew the code worked in at least some cases, because I used the exact same technique to successfully query data from a different XML document. Of all the pieces that could be problematic, I figured the Select() method on the XPathNavigator was probably the most likely culprit. I did a little searching and stumbled upon a bytes article that contained some useful clues.

Fearing that namespaces had something to do with the problem I was seeing, I took a look at the first node in the document I was trying to process. Sure enough, it contained something along the lines of xmlns="http://services.example.com/webservices/" as part of the node definition. With that knowledge and using bits and pieces of the aforementioned article, I made a few changes to my original code:

string namespaceUri = "http://services.example.com/webservices/";
...
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator iter = null;

XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("bz", namespaceUri);

query = "bz:Level1/bz:Level2";
iter = nav.Select(query, ns);
string level2text = (iter.MoveNext()) ? iter.Current.Value : "";

Basically, I created an XmlNamespaceManager and added my own arbitrary namespace ("bz:" because it's just so cool) to it using the namespace provided as part of the xmlns attribute on the XML document's root node. I then prepended that namespace to each node in my XPath query (e.g. "bz:Level1"). I gave the code another shot and sure enough, it worked as expected, extracting the text that I was after.

So let this be a lesson to you. Namespaces in XML can really hose your XPath queries in C# if you aren't careful. Watch out for the xmlns attribute and make use of XmlNamespaceManager as needed to keep your queries thoroughly un-hosed.

Comments

Jordan on June 10, 2009 at 9:10 AM:

This is the exact problem that I've been running into! XPath queries have worked for me in the past and now in one case they just refused to work at all. I think this will help me figure it out. Thanks a lot!

Permalink

Kashif on June 18, 2009 at 4:18 AM:

It didn't work for me at all. I did the exact things above.

Permalink

Rich on August 28, 2009 at 5:49 AM:

Thanks!

I've been struggling with this for most of the morning. Specifying the namespace for every child element seems a bit backwards but it works!

Thanks again!

Permalink

MHedenberg on December 11, 2009 at 9:13 AM:

THANKS!!!! This was exactly the piece I needed to overcome my XPath issue.

Permalink

Robin on May 06, 2010 at 10:09 AM:

Adding the fake prefix solved an annoying issue I was having... thanks!

I'm curious... how come String.Empty with no prefix doesn't work?

For example:

ns.AddNamespace("prfx", "http://www.mysite.com/1.0");
iter = nav.Select("/prfx:booklist/prfx:book", ns);

The above works.. but this doesn't...

ns.AddNamespace(String.Empty, "http://www.mysite.com/1.0");
iter = nav.Select("/booklist/book", ns);


Aren't they pretty much the same thing? It seems counter-intuitive that you have to specify a phony prefix for the default namespace.

Permalink

Robin on May 06, 2010 at 10:15 AM:

Adding the fake prefix solved an annoying issue I was having... thanks!

I'm curious... how come String.Empty with no prefix doesn't work?

For example:

ns.AddNamespace("prfx", "http://www.mysite.com/1.0");
iter = nav.Select("/prfx:booklist/prfx:book", ns);

The above works.. but this doesn't...

ns.AddNamespace(String.Empty, "http://www.mysite.com/1.0");
iter = nav.Select("/booklist/book", ns);


Aren't they pretty much the same thing? It seems counter-intuitive that you have to specify a phony prefix for the default namespace.

Permalink

Robin on May 06, 2010 at 10:16 AM:

Adding the fake prefix solved an annoying issue I was having... thanks!

I'm curious... how come String.Empty with no prefix doesn't work?

For example:

ns.AddNamespace("prfx", "http://www.mysite.com/1.0");
iter = nav.Select("/prfx:booklist/prfx:book", ns);

The above works.. but this doesn't...

ns.AddNamespace(String.Empty, "http://www.mysite.com/1.0");
iter = nav.Select("/booklist/book", ns);


Aren't they pretty much the same thing? It seems counter-intuitive that you have to specify a phony prefix for the default namespace.

Permalink

Robin on May 06, 2010 at 10:16 AM:

Woah.. dunno why I triple posted there.. please delete.

Permalink

flora on December 27, 2011 at 8:30 PM:

thanks a lot.

Permalink

JD Bell on April 23, 2012 at 2:19 PM:

To answer Robin's question (because I had it too), from the MSDN documentation:

"Note If the XmlNamespaceManager will be used for resolving namespaces in an XML Path Language (XPath) expression, a prefix must be specified. If an XPath expression does not include a prefix, it is assumed that the namespace Uniform Resource Identifier (URI) is the empty namespace. For more information about XPath expressions and the XmlNamespaceManager, refer to the XmlNode.SelectNodes and XPathExpression.SetContext methods."

So if you are using XPaths, you MUST use namespace prefixes. I don't know why - seems pretty stupid to me. It's a lot of extra effort for no return, but that's the specs.

Permalink

Joe on September 24, 2012 at 9:45 AM:

Worked for me! Thank you so much!

Permalink

Optician london on August 25, 2016 at 12:36 AM:

Hi, I find reading this article a joy. It is extremely helpful and interesting and very much looking forward to reading more of your work..

Permalink

blog commenting services on September 03, 2016 at 1:25 AM:

Much obliged to you for another incredible article. Where else would anyone be able to get that sort of data in such an impeccable method for composing? I have a presentation one week from now, and I am on the search for such data.

Permalink

cuentas premium minecraft on September 08, 2016 at 12:34 AM:

Awesome study, I'm certain you're getting an extraordinary reaction.

Permalink

free trial netflix on September 08, 2016 at 12:34 AM:

I feel that a debt of gratitude is in order for the valuabe data and bits of knowledge you have so given here.

Permalink

agen judi on March 18, 2017 at 12:27 PM:

Keep on posting more of such updates……

Permalink

السعودية on March 24, 2017 at 12:19 PM:

I really enjoyed reading this post, big fan.

Permalink

seo backlinks service on March 30, 2017 at 2:08 AM:

Nice Informative Blog having nice sharing..

Permalink

replica designer mens messenger bags on April 04, 2017 at 9:06 AM:

Offering wide collection of men designer bags made from high quality materials. Our bags made in Italy and we ship it for free to you.

Permalink

ابتسامة on April 09, 2017 at 12:55 PM:

I will link it back to your website though.Great Thanks.

Permalink

carding forum on April 23, 2017 at 10:53 AM:

Thank you for very usefull information..

Permalink

csgo match betting advice on May 03, 2017 at 4:43 AM:

Bet on an outcome of events in Counter Strike:Global Offensive matches and earn coins for purchasing of skins in the Store.

Permalink

tgxgfobo on May 15, 2017 at 5:23 AM:
versace jeans bags on June 02, 2017 at 1:46 PM:

This is a great article thanks for sharing this informative information.

Permalink

marathi actress on July 28, 2017 at 5:32 AM:

I ' ve never seen a blog that demand a survey for this actions, very curious...

Permalink

The Nora Fashion Handbags on July 31, 2017 at 2:38 AM:

Quality articles is the essential to pull in the general population to visit the site, that?s what this site is giving

Permalink

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.

Name:

Email Address:

Website:

Comments:

Check this box if you hate spam.