.NET XPath queries on XML with a namespace

A quick one here. Wasn’t getting any results when running XPath queries on the following Xml:

<root xmlns="http://www.tempuri.org/xml/export-0.3/">
  <page>...</page>
  <page>...</page>
  <page>...</page>
</root>
Query: "/root/page" or "//page"

As this xml contains a namespace definition you’ll need to pass an instance of the XmlNamespaceManager like so…

XmlDocument xdDoc = new XmlDocument();
xdDoc.Load("Source.xml");

XmlNamespaceManager xnManager =
 new XmlNamespaceManager(xdDoc.NameTable);
xnManager.AddNamespace("tu",
 "http://www.tempuri.org/xml/export-0.3/");

XmlNode xnRoot = xdDoc.DocumentElement;
XmlNodeList xnlPages = xnRoot.SelectNodes("//tu:page", xnManager);
// Assert(xnlPages.Count == 3);
Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s