2012-11-07 84 views
1

我有一些XML是從一個REST調用看起來像這樣返回:如何使用XElement.Parse然後找到特定元素的值?

<ArrayOfProperty xmlns=\"http://schemas.microsoft.com/HPCS2008R2/common\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"> 
    <Property> 
    <Name>Id</Name> 
    <Value>17</Value> 
    </Property> 
    <Property> 
    <Name>StartTime</Name> 
    <Value>11/7/2012 9:13:50 PM</Value> 
    </Property> 
    <Property> 
    <Name>State</Name> 
    <Value>Failed</Value> 
    </Property> 

我使用RestSharp API,以協助執行API調用,並試圖使用LINQ-TO- xml XElement.Parse解析結果。我不知道如何獲得狀態的值,以便從本文檔中我想要執行類似的操作:

XElement.Parse(XMLstring).Elements???從包含元素狀態的元素集合中獲取文本「失敗」,但是我想要<Value>Failed</Value>元素中的文本「失敗」。該值元素可以有多個值,但我總是希望與該狀態關聯的值。

任何想法?

回答

1

您的XML包含默認名稱空間,所以您需要定義它並在查詢中使用。

XNamespace ns = "http://schemas.microsoft.com/HPCS2008R2/common"; 

var value = (string)XDocument.Parse(input) 
    .Descendants(ns + "Property") 
    .Where(p => (string)p.Element(ns + "Name") == "State") 
    .Elements(ns + "Value").FirstOrDefault(); 
+1

太棒了!非常感謝;這件事我一直在喋喋不休。 –

+1

@ChrisTownsend,不客氣! –

相關問題