Thursday, 6 August 2009

Using Linq lambda expressions to retrieve XML elements based on the value of an attribute

The following example program loads an XML file, then selects all the elements named "field" within it. It then uses a lambda expression to get the inner text of the "alternativeTitle" element.

class Program
static void Main( string[] args )
XDocument xd = XDocument.Load( "..\\..\\file.xml" );

var fields = from el in xd.Descendants()
where el.Name.ToString().StartsWith( "field" )
select el;

Console.WriteLine( GetElementValue(fields, "alternativeTitle") );

static string GetElementValue( IEnumerable<XElement> elements, string attributeName )
return elements.Single( p => p.Attributes().Single( q => q.Name == "name" ).Value == attributeName ).Value;

The XML file used in the example is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<field name="id">some_id</field>
<field name="readableid">interesting_publications</field>
<field name="name">Interesting Publications</field>
<field name="alternativeTitle">Online publications</field>

The program outputs the text:

Online publications

No comments: