.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/">
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();

XmlNamespaceManager xnManager =
 new XmlNamespaceManager(xdDoc.NameTable);

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

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 )

Connecting to %s