XmlDocument and XPath

Briefly, first time with XPath looks great, and it is, but when you start coding it is not so easy.
Good news, you just need a lit bit more 🙂

Example: you have a few webservices given similar xml response:

<MyResponse>
  <ResponseMessage />
  <ResponseCode />
  <!-- put custom xml here -->
  <ServerID />
  <RequestID />
</MyResponse>

What if you want to log which server run your request?
Sample code could be like this

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xmlString);
foreach (XmlElement xItem in xdoc.SelectNodes("//ServerID"))
{
  // do sth
}

Actually, SelectNodes methods return no nodes, and XPath it’s almost right.
XPath query string miss namespace specs, so xpath query will look for node with empty namespace.

A quick ‘n dirty sample code could be like this:

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xmlString);
XmlNamespaceManager nsmanager = new XmlNamespaceManager(xdoc.NameTable);
nsmanager.AddNamespace("x", xdoc.DocumentElement.Attributes["xmlns"].Value);
foreach (XmlElement xItem in xdoc.SelectNodes("//x:ServerID"))
{
  // do sth here
}

where XPath query string report namespace

Read more here: Xml-SelectNodes with default-namespace via XmlNamespaceManager not working as expected

Technorati tags: XML,XPath
Advertisements

Tags: , ,

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: