You need to use also the XElement.Attribute property. I would create an extension method that looks like this:
public static class ProjectExtensions
{
public static String GetValue(this XDocument source, String name, String value)
{
// return source
// .Root
// .Element(name)
// .Elements("item")
// .Where (f => f.Attribute("address").Value == value)
// .FirstOrDefault()
// .Value;
// or alternative
var result = (from e in source.Root.Element(name).Elements("item")
where e.Attribute("address").Value == value
select e.Value).FirstOrDefault();
return result;
}
}
Then the usage looks like this:
var xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<bar>
<foo>
<item address=""123"">AAA foo</item>
</foo>
<definitions>
<item address=""123"">AAA definition</item>
<item address=""456"">BBB</item>
</definitions>
</bar>";
try
{
var document = XDocument.Parse(xml);
Console.WriteLine(document.GetValue("foo", "123"));
Console.WriteLine(document.GetValue("definitions", "123"));
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
The output is:
AAA foo
AAA definition
Consider adding exception handling and checks to prevent errors. The LINQ fluent and query syntax are in this case (almost) identical.