Linq to XML - Retrieving a Single Element

I have an XML / Soap file that looks like this:

<?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> <SendData xmlns="http://stuff.com/stuff"> <SendDataResult>True</SendDataResult> </SendData> </soap:Body> </soap:Envelope> 

I want to extract the SendDataResult value, but I am having difficulty with this code and various other methods that I tried. It always returns null, even if the element has a value.

 XElement responseXml = XElement.Load(responseOutputFile); string data = responseXml.Element("SendDataResult").Value; 

What you need to do to retrieve the SendDataResult element.

+4
source share
1 answer

You can use Descendants and then First or Single - you are currently requesting a top-level element whether it received a SendDataResult element directly below it, but it is not. Also, you are not using the correct namespace. This should fix this:

 XNamespace stuff = "http://stuff.com/stuff"; string data = responseXml.Descendants(stuff + "SendDataResult") .Single() .Value; 

Alternatively, go directly to:

 XNamespace stuff = "http://stuff.com/stuff"; XNamespace soap = "http://www.w3.org/2003/05/soap-envelope"; string data = responseXml.Element(soap + "Body") .Element(stuff + "SendDataResult") .Value; 
+5
source

All Articles