Skip to main content
 首页 » 编程设计

c#之使用 C# 解析 SOAP 响应

2024年02月23日13mayingbao

我一直在尝试使用来自 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> 

我需要的是 Products 中的内容(目前)。

我正在尝试使用 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; 

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

任何线索将不胜感激。

谢谢。

请您参考如下方法:

在您的 XML 中,StoreProducts 不在 XML namespace 内,只需执行以下操作:

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

如果内部 XML 如下所示,您提供的示例代码将会成功:

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