remove soap envelope header and get the XML

I have a soap response, I want to remove all soap related things and get the inner XML with only one header.

response:

"<s:Envelope xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
    <s:Body>
        <getResponse xmlns = ""http://tempuri.org/"">
            <getResult xmlns:xsi = ""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd = ""http://www.w3.org/2001/XMLSchema"">
                <Id>999</Id>
                <EResponse>
                    <au>
                        <st>ABC</st>
                        <co>DGH</co>
                        <mo>MMM</mo>
                    </au>
         </EResponse>
            </getResult>
        </getResponse>
    </s:Body>
</s:Envelope> 
          

I want to extract this:

<getResult xmlns:xsi = ""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd = ""http://www.w3.org/2001/XMLSchema"">
                <Id>999</Id>
                <EResponse>
                    <au>
                        <st>ABC</st>
                        <co>DGH</co>
                        <mo>MMM</mo>
                    </au>
         </EResponse>
            </getResult>

I am trying this:

XDocument input;

      using (var nodeReader = new XmlNodeReader(doc))
        {
            nodeReader.MoveToContent();
            input = XDocument.Load(nodeReader);
        }

        var xns = XNamespace.Get("http://tempuri.org/");
        var SoapBody = input.Descendants(xns + "getResult").First().ToString();

but I am also getting namespace tempuri appended in getresult tag, which I don't want or any other way to achieve it ?

1 answer

  • answered 2020-09-23 10:36 jdweng

    Try following :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.IO;
    
    namespace ConsoleApplication169
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                string xml = File.ReadAllText(FILENAME);
                XDocument doc = XDocument.Parse(xml);
    
    
                XElement results = doc.Descendants().Where(x=> x.Name.LocalName == "getResult").FirstOrDefault();
                XNamespace ns = results.GetDefaultNamespace();
    
                string id = (string)results.Element(ns + "Id");
    
                Dictionary<string, string> au = results.Descendants(ns + "au").FirstOrDefault().Elements()
                    .GroupBy(x => x.Name.LocalName, y => (string)y)
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
    
            }
        }
    }