Posts Tagged ‘XPath’

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
  • June 2017
    M T W T F S S
    « Dec    
     1234
    567891011
    12131415161718
    19202122232425
    2627282930  
  • .

    .Net Agile Antivirus Book C# Programming EntityFramework GTD Hyper-V LinQ MVVM Office Resharper SCRUM Security Sharepoint Silverlight SQLServer TFS ToDoList Unit Test VirtualBox Virtual PC Visual Studio VMware Windows7 WPF XeDotNet XML XPath