2011-01-05 8 views
1

LINQ - クエリー要素私は、文字列を取得する必要が上記のXML "Book1.out" で

<Contents> 
    <Content Book="ABC"> 
     <Item type="New" id="1" File="book1.out"/> 
     <Item type="Old" id="2" File="book1.out"/> 
    </Content 
</Contents> 

が出力 など条件がある場合ブック= "ABC"とID = "1"

これをLINQでワンショットで行う方法結果を評価する。

この私の最初のコード:

var result = (from query in _configDoc.Descendants("Contents").Descendants("Content") 
       where query.Attribute("Book").Value == "ABC") select query; 

おかげ..

+0

とあなたの最初のコードの農産物を何? –

答えて

1

属性ブック= "ABC" とid = 1とItem要素の値を取得するには:

var result = _configDoc.Descendants("Content") 
    .Where(c => c.Attribute("Book").Value == "ABC") 
    .Descendants("Item").Single(e => e.Attribute("id").Value == "1").Value; 

これは、属性をヌルチェックしない単純なバージョンです。また、実際のシナリオに応じて、XPath式が簡単になります。

+0

Hi Driis、Book == "ABC"は別のノードにあり、idは別のノードにあります。 <コンテンツブック= "ABC"> – dps123

+0

ええ、今それを捕まえました:-) – driis

+0

Driis ..ありがとう.. 。 – dps123

0

あなたはLINQをスキップして、このように、代わりにXPathを使用することができます

using System.Xml.XPath; 

... 
var result = _configDoc.XPathEvaluate("/Contents/Content[@Book='ABC']/Item[@ID='1']/@File"); 
+0

こんにちはローレンス、ご返信ありがとうございます。一貫性を維持するために、私は自分のコードでLINQを使用しなければなりませんでした。 – dps123

関連する問題