Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# and XDocument/XElement to parse a Soap Response

Tags:

c#

soap

parsing

xml

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 grab the Descendant or Element of "Result" I get null. Does it have something to do with the Namespace? Can someone provide a solution to retrieve Result from this?

like image 920
strickland Avatar asked Apr 23 '09 01:04

strickland


3 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

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.

like image 62
Justin Niessner Avatar answered Nov 13 '22 06:11

Justin Niessner


to extend Justin's answer with tested code with a return that excpects a boolean and that the response and result start with the method name (BTW - a surprise is even thought the XML element does not show the NS it 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;
        }
    }
like image 4
azpc Avatar answered Nov 13 '22 06:11

azpc


Maybe like this:

IEnumerable<XElement> list = doc.Document.Descendants("Result");
if (list.Count() > 0)
{
    // do stuff
}
like image 1
Paw Baltzersen Avatar answered Nov 13 '22 07:11

Paw Baltzersen