Posts Tagged ‘XML’

XmlDocument and XPath

September 19, 2012

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