Succinct LINQ to XML Query

Posted by Kent Boogaart on Stack Overflow See other posts from Stack Overflow or by Kent Boogaart
Published on 2010-04-21T16:07:55Z Indexed on 2010/04/21 16:23 UTC
Read the original article Hit count: 126

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about linq-to-xml

Related posts about c#