سؤال

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;
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top