2011-07-19 34 views
4

我有一個XML /香皂文件看起來像這樣:的LINQ to XML - 提取單元

<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <soap:Body> 
    <SendData xmlns="http://stuff.com/stuff"> 
     <SendDataResult>True</SendDataResult> 
    </SendData> 
    </soap:Body> 
</soap:Envelope> 

我想提取的SendDataResult價值,但我有困難與下面的代碼等各種方式這樣做我試過了。即使元素中有一個值,它總是返回null。

XElement responseXml = XElement.Load(responseOutputFile); 
string data = responseXml.Element("SendDataResult").Value; 

需要做些什麼來提取SendDataResult元素。

回答

5

您可以使用後跟FirstSingleDescendants - 目前你問頂級元素無論是直接得到了SendDataResult元素在它下面,它沒有。另外,你沒有使用正確的命名空間。這應該可以解決它:

XNamespace stuff = "http://stuff.com/stuff"; 
string data = responseXml.Descendants(stuff + "SendDataResult") 
         .Single() 
         .Value; 

或者,直接導航:

XNamespace stuff = "http://stuff.com/stuff"; 
XNamespace soap = "http://www.w3.org/2003/05/soap-envelope"; 
string data = responseXml.Element(soap + "Body") 
         .Element(stuff + "SendDataResult") 
         .Value;