2016-08-17 85 views
1

我正在嘗試讀取此xml消息中的APP_DATE元素。使用LINQ嘗試,但無法讀取,因爲你沒有提供任何示例代碼,但我相信你,因爲命名空間的鬥爭MyResult從SOAP消息中讀取元素

<?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> 
<MyResponse xmlns="http://tempuri.org/"> 
<MyResult> 
    <APP_TYPE>I</APP_TYPE> 
    <APP_NO>152240</APP_NO> 
    <APP_DATE>10/03/2016</APP_DATE> 
    </MyResult> 
    </MyResponse> 
    </soap:Body> 
</soap:Envelope> 

回答

1

不能肯定。所以,試試這個:

XmlDocument doc = new XmlDocument(); 
doc.Load("data.xml"); 
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); 
ns.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope"); 
ns.AddNamespace("x", "http://tempuri.org/"); 

var result = doc.SelectSingleNode("//soap:Envelope/soap:Body/x:MyResponse/x:MyResult/x:APP_DATE", ns).InnerText; 

爲了更深入的瞭解,你可以閱讀this question

使用LINQ這將是這樣的:

var result = XDocument.Load("data.xml").Root 
         .Descendants(XName.Get("APP_DATE", "http://tempuri.org/")) 
         .FirstOrDefault()?.Value; 

瞭解如何在這兩個例子中我有指定的命名空間我在找什麼

+0

「?」是什麼意思?在你的linq querry做什麼? – gismo

+1

@ gismo - 它是c#6.0的'x == null的語法糖嗎?/* x */x.Value類型的默認值。你可以在[MSDN](https://msdn.microsoft.com/en-us/magazine/dn802602.aspx)中準備好它, –