使用C#解析SOAP响应

时间:2011-07-27 01:30:43

标签: c# soap response

我一直在尝试使用API​​中的数据,但我无法从中读取XML响应。

它出现在以下形式:

    <?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>

我需要的是产品内部(现在)。

我试图在没有结果的情况下使用Using C# to parse a SOAP Response(以及其他人不会淹没这个)。

我的代码:

    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;

我几乎可以肯定我错过了一些基本的东西。

任何线索都会非常感激。

谢谢。

3 个答案:

答案 0 :(得分:2)

在您的XML中StoreProducts不在XML命名空间内,只需执行:

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

如果内部XML看起来像这样,那么您提供的示例代码就会成功:

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

答案 1 :(得分:1)

您确定需要解析XML吗? 使用c#proxy处理SOAP非常有效。

你有没有看过svcutil.exe来生成代理?

答案 2 :(得分:0)

在我的情况下,我需要它来阅读发布请求中发送的xml

        // 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;