0

我从网络服务中得到了一个特殊的响应:

<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>
    <GetLemonadeResponse xmlns="http://microsoft.com/webservices/">
      <GetLemonadeResult>&lt;Response&gt;&lt;Status&gt;Error&lt;/Status&gt;&lt;Message&gt;Could not find the Lemonade for this State/Lemon&lt;/Message&gt;&lt;FileNumber /&gt;&lt;/Response&gt;</GetLemonadeResult>
    </GetLemonadeResponse>
  </soap:Body>
</soap:Envelope>

2个问题:

1)我不确定为什么 GetLemonadeResult 的内容有异常内容(如“& lt;”)。

我以这种方式将字节迁移到字符串:

WebClientEx client = new WebClientEx();
client.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8");
client.Encoding = Encoding.UTF8;
byte[] result = client.UploadData(_baseUri.ToString(), data);
client.Encoding.GetBytes(xml));
string resultString = client.Encoding.GetString(result);

(WebClientEx 派生自带有额外 Timeout 属性的 WebClient)。

我在想如果我选择了错误的编码,响应的外部部分也会以同样的方式被破坏。

网络服务是否有错误?

2) 为什么当我尝试使用 Linq to XML 抓取“GetLemonadeResult”时,它什么也拉不出来?

var xdoc = XDocument.Parse(response); // returns the XML posted above
var responseAsXML = xdoc.Descendants("GetLemonadeResult"); // gets nothing

我不会猜到我需要一个命名空间来捕获后代,因为 XML GetLemonadeResult 标记没有前置“标记:”。

4

1 回答 1

2

1)一些可以使 xml 无效的字符如 <,> 等被转义

2)您忘记在代码中包含命名空间

var xdoc = XDocument.Parse(response);
XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace ns = "http://microsoft.com/webservices/";
var responseAsXML = xdoc.Descendants(soap + "Body")
                        .Descendants(ns + "GetLemonadeResult")
                        .First().Value;

responseAsXML将会

<Response>
<Status>Error</Status>
<Message>Could not find the Lemonade for this State/Lemon
</Message><FileNumber />
</Response>

编辑

这是我用来测试的soap/xml

string response = @"<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>
                        <GetLemonadeResponse xmlns=""http://microsoft.com/webservices/"">
                            <GetLemonadeResult>&lt;Response&gt;&lt;Status&gt;Error&lt;/Status&gt;&lt;Message&gt;Could not find the Lemonade for this State/Lemon&lt;/Message&gt;&lt;FileNumber /&gt;&lt;/Response&gt;</GetLemonadeResult>
                        </GetLemonadeResponse>
                        </soap:Body>
                    </soap:Envelope>";
于 2013-04-24T19:48:43.450 回答