2014-01-11 102 views
0

如何使用linq返回特定'作者'的所有「標題」值?Xml linq查詢基於2元素

<Details xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Record> 
    <Author>Barry White</Author> 
    <Title>First Book</Title> 
    </Record> 
    <Record> 
    <Author>Barry White</Author> 
    <Title>Second Book</Title> 
    </Record> 
    <Record> 
    <Author>Norman White</Author> 
    <Title>Second Book</Title> 
    </Record> 
</Details> 

回答

2
var xDoc = XDocument.Load("Input.xml"); 

var author = "Barry White"; 
var titles = (from r in xDoc.Root.Elements("Record") 
       let _author = (string)r.Element("Author") 
       let _title = (string)r.Element("Title") 
       where _author == author 
       select _title).ToList(); 

或使用方法爲基礎的查詢:

var titles = xDoc.Root.Elements("Record") 
       .Where(r => (string)r.Element("Author") == author) 
       .Select(r => (string)r.Element("Title")) 
       .ToList(); 
+0

很好,謝謝您的幫助,並快速作出迴應, – matinau

2

您可以使用LINQ to XML

var titles = XDocument.Parse(inputxml) 
         .Descendants("Record") 
         .Where(x => x.Element("Author").Value == "Barry White") 
         .Select(x => x.Element("Title").Value) 
         .ToList(); 
+0

你不應該使用'後裔'就是這樣。 – MarcinJuraszek

+0

@MarcinJuraszek:因爲...... –

+0

@RobertHarvey因爲它使得查詢效率低下 – MarcinJuraszek