0

I have a xml where i want to select a node from it here is the xml:

  <?xml version="1.0" encoding="utf-8" ?> 
  <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
  <InResponse xmlns="https://ww.ggg.com">
  <InResult>Error </InResult> 
  </InResponse>
  </soap:Body>
  </soap:Envelope>

I am loading it using XmlDocument's LoadXML and trying to get InResult node but I get null see below please:

xml.SelectSingleNode("//InResult").InnerText;
Zaki
  • 5,540
  • 7
  • 54
  • 91

2 Answers2

3

You have a namespace declaration and you should add this into your XPath or you can use namespace agnostic XPath. Try next code as namespace agnostic solution:

xml.SelectSingleNode("//*[local-name()='InResult']").InnerText;

I've received Error as result

From http://www.w3schools.com/ site:

local-name() - Returns the name of the current node or the first node in the specified node set - without the namespace prefix

You can get more information about XPath functions here.

Namespace aware solution, is given below:

var namespaceManager = new XmlNamespaceManager(x.NameTable);
namespaceManager.AddNamespace("defaultNS", "https://ww.ggg.com");

var result = x.SelectSingleNode("//defaultNS:InResponse", namespaceManager).InnerText;
Console.WriteLine (result); //prints Error

Brief XML notes:

This part in root note xmlns:soap="http://www.w3.org/2003/05/soap-envelope" is a xml namespace declaration. It is used to identify nodes in your xml structure. As a rule, you need to specify them to access nodes with it, but there are namespace agnostic solutions in XPath and in LINQ to XML. Now if you see node name as <soap:Body>, this means, that this node belongs to this namespace.

Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
1

This seems to be an namespace issue You can use an XmlNamespaceManager before you call SelectSingleNode():

XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
ns.AddNamespace("ggg", "https://ww.ggg.com");
xml.SelectSingleNode("//ggg:InResult", ns).InnerText;

Attention: Not tested.

hr_117
  • 9,589
  • 1
  • 18
  • 23
  • you should pass `ggg` into Xpath, not `ns`. `ns` - is a variable name and XPath evaluation engine knows nothing about it. – Ilya Ivanov Jun 03 '13 at 14:18