2013-04-24 38 views
0

我得到一個特殊的響應返回從Web服務:解析不尋常的XML使用LINQ

<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的含量有異常的內容(如「& 「)。

我字節遷移到字符串是這樣的:

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從Web客戶端派生一個額外的超時屬性)。

我在想,如果我選錯了編碼,響應的外部部分將以同樣的方式被損壞。

Web服務是否有錯誤?

2)爲什麼當我嘗試使用Linq to XML獲取「GetLemonadeResult」時,它無法拉取任何東西?

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

我根本看不出我需要一個命名空間趕後裔,因爲XML GetLemonadeResult標籤沒有預謀「標籤」。

+0

我沒有看到 「GetClosingProtectionLetterResult」 在你的例子迴應? – cgatian 2013-04-24 19:41:20

+0

'GetClosingProtectionLetterResult'在您提供的示例XML中不存在。請用包含它的XML更新您的問題。 – 2013-04-24 19:41:40

+0

@cgtian:這麼多是爲了掩飾我來自哪個行業!道歉... – micahhoover 2013-04-24 19:49:37

回答

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> 

EDIT

這是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>"; 
+0

@micahhoover我在你的問題中使用了soap/xml,它返回了我發佈的xml。我編輯了答案。 – I4V 2013-04-24 20:11:16

+1

謝謝。我在我的最後犯了一個愚蠢的錯誤。信封不需要明確地「下降」。 – micahhoover 2013-04-24 20:20:45