2014-01-11 101 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