Succinct LINQ to XML Query
- by Kent Boogaart
Assuming you have the following XML:
<?xml version="1.0" encoding="utf-8"?>
<content>
<info>
<media>
<image>
<info>
<imageType>product</imageType>
</info>
<imagedata fileref="http://www.example.com/image1.jpg" />
</image>
<image>
<info>
<imageType>manufacturer</imageType>
</info>
<imagedata fileref="http://www.example.com/image2.jpg" />
</image>
</media>
</info>
</content>
Using LINQ to XML, what is the most succinct, robust way to obtain a System.Uri for an image of a given type? At the moment I have this:
private static Uri GetImageUri(XElement xml, string imageType)
{
return (from imageTypeElement in xml.Descendants("imageType")
where imageTypeElement.Value == imageType && imageTypeElement.Parent != null && imageTypeElement.Parent.Parent != null
from imageDataElement in imageTypeElement.Parent.Parent.Descendants("imagedata")
let fileRefAttribute = imageDataElement.Attribute("fileref")
where fileRefAttribute != null && !string.IsNullOrEmpty(fileRefAttribute.Value)
select new Uri(fileRefAttribute.Value)).FirstOrDefault();
}
This works, but feels way too complicated. Especially when you consider the XPath equivalent.
Can anyone point out a better way?