Parsing a SOAP Response with C#

匆匆过客 提交于 2021-02-19 09:01:32

问题


I've been trying to use the data from an API but I have not been able to read the XML Response from it.

It cames in the form:

    <?xml version="1.0" standalone="no"?>
        <SOAP-ENV:Envelope xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema" xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
        <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
            <SOAPSDK4:GetStoreProductsResponse xmlns:SOAPSDK4="http://www.externalwebservice.com/message/">
                <StoreProducts>
                    <StoreID></StoreID>
                    <Products></Products>
                </StoreProducts>
            </SOAPSDK4:GetStoreProductsResponse></SOAP-ENV:Body>
        </SOAP-ENV:Envelope>

And what I need is what is inside Products (for now).

I was trying to use Using C# to parse a SOAP Response (and others to not flood this) without results.

My code:

    XDocument tst = XDocument.Load("Response.xml");
    XNamespace xmlns = "http://schemas.xmlsoap.org/soap/envelope/";
    var tstr = from result in tst.Descendants(xmlns + "StoreProducts") select result.Element("Products").Value;

I am almost sure that I am missing something basic.

Any clue will be really appreciated.

Thank you.


回答1:


In your XML StoreProducts is not within an XML namespace, just do :

var tstr = from result in tst.Descendants("StoreProducts") 
           select result.Element("Products").Value;

The example code you gave would have been successful if the inner XML looked like this:

  <SOAP-ENV:StoreProducts>
    <StoreID></StoreID>
    <Products></Products>
  </SOAP-ENV:StoreProducts>



回答2:


Are you sure you need to parse XML ? .NET is very efficient to handle SOAP using c# proxy.

Have you looked to svcutil.exe to generate a proxy ?




回答3:


In my case I need it to read the xml sent in the post request

        // read the raw request
        Request.InputStream.Seek(0, SeekOrigin.Begin);
        string xmlPayload = new StreamReader(Request.InputStream).ReadToEnd();
        XDocument doc = XDocument.Parse(xmlPayload);

        XNamespace xmlns = "urn:sobject.enterprise.soap.sforce.com";
        item.sfId = doc.Descendants(xmlns + "Id").First().Value;
        item.AccountId = doc.Descendants(xmlns + "AccountId").First().Value;
        item.FirstName = doc.Descendants(xmlns + "FirstName").First().Value;
        item.LastName = doc.Descendants(xmlns + "LastName").First().Value;
        item.XmlPayload = xmlPayload;


来源:https://stackoverflow.com/questions/6838504/parsing-a-soap-response-with-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!