Mohit Dhawan
Mohit Dhawan

Reputation: 543

Get XML Child Node Value from soapxml

From last couple of days I was trying to extract err:Errors from following XML using c#

I am using UPS webs services and when I cancel pickup I am getting this XML as return

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header />
  <soapenv:Body>
    <soapenv:Fault>
      <faultcode>Client</faultcode>
      <faultstring>An exception has been raised as a result of client data.</faultstring>
      <detail>
        <err:Errors xmlns:err="http://www.ups.com/XMLSchema/XOLTWS/Error/v1.1">
          <err:ErrorDetail>
            <err:Severity>Hard</err:Severity>
            <err:PrimaryErrorCode>
              <err:Code>9510131</err:Code>
              <err:Description>Order has already been canceled</err:Description>
            </err:PrimaryErrorCode>
          </err:ErrorDetail>
        </err:Errors>
      </detail>
    </soapenv:Fault>
  </soapenv:Body>
</soapenv:Envelope>

but cannot find any relevant solution.

This is what I tried:

XmlDocument xDoc = new XmlDocument(); 
xDoc.LoadXml(strResponse); 
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(xDoc.NameTable);
xDoc.SelectSingleNode(
     "soapenv:Envelope/soap‌​env:Body/soapenv:Fault/err:ErrorDetail",
      xmlnsManager).InnerText;

It looks like the SelectSingleNode returns nothing.

Upvotes: 2

Views: 1079

Answers (1)

rene
rene

Reputation: 42494

You have to add the namespaces to your NamespaceManager:

xmlnsManager.AddNamespace("soapenv","http://schemas.xmlsoap.org/soap/envelope/");
xmlnsManager.AddNamespace("err","http://www.ups.com/XMLSchema/XOLTWS/Error/v1.1");

xDoc.SelectSingleNode(
 "/soapenv:Envelope/soap‌​env:Body/soapenv:Fault/err:ErrorDetail",
  xmlnsManager).InnerText;

before you call SelectSingleNode. Make sure you synchronize the namespace aliases in your namespacemanager with the alias used in your XPATH expression.

Upvotes: 4

Related Questions