2011-01-05 223 views
1

的LINQ to XML - 查詢元素

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

在上面的XML我需要得到字符串 「Book1.out」 作爲輸出 有WHERE條件本書=「美國廣播公司」和ID =「1」

如何在LINQ中做到這一點,沒有迭代對結果進行評分。

這是我最初的代碼:

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

謝謝..

+0

的,什麼是你最初的代碼產生? – 2011-01-05 21:07:48

回答

1

要獲得屬性書= 「ABC」 和id的item元素= 1的值:

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

這是直接的版本,沒有對屬性進行空值檢查。另外,根據您的實際情況,XPath表達式可能更簡單。

+0

嗨Driis,書==「ABC」是不同的節點ID是在不同的節點 <內容賬面=「ABC」> – dps123 2011-01-05 21:12:48

+0

呀,抓到現在:-) – driis 2011-01-05 21:15:00

+0

它的工作原理Driis ..謝謝.. – dps123 2011-01-05 22:49:58

0

你可以跳過LINQ和使用XPath,而不是像這樣:

using System.Xml.XPath; 

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

嗨勞倫斯,謝謝你的回覆。爲了保持一致性,我必須在代碼中使用LINQ。 – dps123 2011-01-05 22:51:38