0

I am trying to get Absoluteentry tag's value from the below xml string, but its displaying objectrefrence not set exception

<?xml version="1.0" ?> 
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
  <env:Body>
    <AddResponse xmlns="http://www.sap.com/SBO/DIS">
      <PickListParams>
        <Absoluteentry>120072</Absoluteentry> 
      </PickListParams>
    </AddResponse>
  </env:Body>
</env:Envelope>

Code

XDocument doc = XDocument.Parse(xmlstring);
doc.Element("Envelope").Element("Body").Element("AddResponse").Element("PickListParams").Element("Absoluteentry").Value;
Tim
  • 28,212
  • 8
  • 63
  • 76
Edwin O.
  • 4,998
  • 41
  • 44
  • You need to set the namespaces for the elements - see http://stackoverflow.com/a/2340497/745969 for an example – Tim May 18 '15 at 19:06
  • possible duplicate of [Use Linq to Xml with Xml namespaces](http://stackoverflow.com/questions/2340411/use-linq-to-xml-with-xml-namespaces) – Tim May 18 '15 at 19:06

2 Answers2

6

Look at the XML:

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
...

That's the Envelope element in the namespace with URI "http://www.w3.org/2003/05/soap-envelope".

Now look at your code:

doc.Element("Envelope")...

That's looking for an Envelope element that's not in any namespace. You should specify the namespace - and the namespaces of the other elements you're looking for:

XNamespace env = "http://www.w3.org/2003/05/soap-envelope";
XNamespace responseNs = "http://www.sap.com/SBO/DIS";
XDocument doc = XDocument.Parse(xmlstring);
var result = doc.Element(env + "Envelope")
    .Element(env + "Body")
    .Element(responseNs + "AddResponse")
    .Element(responseNs + "PickListParams")
    .Element(responseNs + "Absoluteentry").Value;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

You can use Descendants too. Descendants finds children at any level.

var result = doc.Element(env + "Envelope")
    .Element(env + "Body")
    .Descendants(responseNs + "Absoluteentry").Value;
Luis Hernandez
  • 453
  • 5
  • 8