2012-04-27 76 views
1

我想從使用LINQ的XML文件讀取值。 這真的是我第一次嘗試使用LINQ與普通的C#/ .Net方法。使用LINQ讀取XML元素

我的XML看起來是這樣的:

<Description> 
<Account Green="A" White="D">House</Account> 
<Account Green="B" White="D">Car</Account> 
</Description> 

這是我使用的LINQexpression。我想讀House的價值,換句話說,屬性A和D的元素。

var feeds = (from item in doc.Descendants("Description") 
from category in item.Elements("Account")      
let attribute = category.Attribute("Green")      
let xAttribute = category.Attribute("White")      
where attribute != null && (xAttribute != null && (xAttribute.Value == "A" 
&& attribute.Value == "D")) select item.Value).ToString(); 

我弄不明白我做錯了什麼。 任何幫助表示讚賞。

+0

它是XmlElement還是XElement? – Gqqnbig 2017-03-13 23:22:07

回答

1

您這裏有一個IEnumerable<string> - 你顯然只想一個字符串這裏,所以添加First()讓你列舉的第一項的值:

var feeds = (from item in doc.Descendants("Description") 
from category in item.Elements("Account")      
let attribute = category.Attribute("Green")      
let xAttribute = category.Attribute("White")      
where attribute != null && (xAttribute != null && (xAttribute.Value == "A" 
&& attribute.Value == "D")) select category.Value).First(); 

更簡單的方法來達到同樣的可能:

string result = doc.Descendants("Account") 
        .Where(x => x.Attribute("Green") != null && x.Attribute("Green").Value == "A" 
          && x.Attribute("White") != null && x.Attribute("White").Value == "D") 
        .Select(x => x.Value) 
        .First(); 
+0

@SaeedAmiri:不 - 'item.Value'已經是'string'類型了 – BrokenGlass 2012-04-27 21:17:02

+0

但是這給了我GreenWhite。就像以前一樣。 – user1017102 2012-04-27 21:21:34

+0

@ user1017102:固定 - 需要選擇'category.Value'而不是'item.Value' – BrokenGlass 2012-04-27 21:23:04