2012-04-27 9 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です。私は価値ハウスを読みたい、つまり、属性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

答えて

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

+0

しかし、これは私にGreenWhiteを与えます。以前と同じように。 – user1017102

+0

@ user1017102:修正済み - 'item.Value'ではなく' category.Value'を選択する必要があります – BrokenGlass

関連する問題