Reputation: 335
How can I return all the "Title" values for a particular 'Author' using linq ?
<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>
Upvotes: 0
Views: 58
Reputation: 16878
You can use 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();
Upvotes: 2
Reputation: 125630
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();
or using method-based query:
var titles = xDoc.Root.Elements("Record")
.Where(r => (string)r.Element("Author") == author)
.Select(r => (string)r.Element("Title"))
.ToList();
Upvotes: 2