Using C # and XDocument / XElement to parse a soap response

Here is a sample soap response from my SuperDuperService:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <MyResponse xmlns="http://mycrazyservice.com/SuperDuperService"> <Result>32347</Result> </MyResponse> </soap:Body> </soap:Envelope> 

For some reason, when I try to capture a descendant or a "result" element, I get null. Does this have anything to do with the namespace? Can someone provide a solution to extract the result from this?

+3
source share
4 answers

You might want to try something like this:

 string myNamespace= "http://mycrazyservice.com/SuperDuperService"; var results = from result in yourXml.Descendants(XName.Get("MyResponse", myNamespace)) select result.Element("Result").value 

You don't have VS on this laptop, so I can't double check my code, but it should point you in the right direction using LINQ to SQL.

+10
source

to extend Justin's answer with verified return code that checks the boolean and that the response and result starts with the method name (BTW - the surprise is even considered that the XML element does not show the NS that requires it when parsing)

  private string ParseXml(string sXml, string sNs, string sMethod, out bool br) { br = false; string sr = ""; try { XDocument xd = XDocument.Parse(sXml); if (xd.Root != null) { XNamespace xmlns = sNs; var results = from result in xd.Descendants(xmlns + sMethod + "Response") let xElement = result.Element(xmlns + sMethod + "Result") where xElement != null select xElement.Value; foreach (var item in results) sr = item; br = (sr.Equals("true")); return sr; } return "Invalid XML " + Environment.NewLine + sXml; } catch (Exception ex) { return "Invalid XML " + Environment.NewLine + ex.Message + Environment.NewLine + sXml; } } 
+3
source

Maybe so:

 IEnumerable<XElement> list = doc.Document.Descendants("Result"); if (list.Count() > 0) { // do stuff } 
+1
source

You are looking in the right direction, it is definitely related to the namespace.

The code below returns the first element found for a combination of namespace and element name.

 XDocument doc = XDocument.Load(@"c:\temp\file.xml"); XNamespace ns = @"http://mycrazyservice.com/SuperDuperService"; XElement el = doc.Elements().DescendantsAndSelf().FirstOrDefault( e => e.Name == ns + "Result"); 
+1
source

All Articles