简体   繁体   English

编写Linq2Xml查询的问题

[英]Problem Writing Linq2Xml Query

I'm trying to write a Linq2XML query to query the following XML. 我正在尝试编写Linq2XML查询来查询以下XML。 I need it to pull back all photos for a given GalleryID. 我需要它来拉回给定GalleryID的所有照片。

<Albums>
<Album GalleryId="1" Cover="AlbumCover1.jpg" Title="Album 1">
    <Photos>
        <Photo Title="Image1" URL="img1.jpg" DateAdded="01/01/2010 09:20"/>
        <Photo Title="Image2" URL="img2.jpg" DateAdded="01/01/2010 09:20"/>
        <Photo Title="Image3" URL="img3.jpg" DateAdded="01/01/2010 09:20"/>
    </Photos>
</Album>
<Album GalleryId="2" Cover="AlbumCover1.jpg" Title="Album 2">
    <Photos>
        <Photo Title="Image1" URL="img1.jpg" DateAdded="01/01/2010 09:20"/>
        <Photo Title="Image2" URL="img2.jpg" DateAdded="01/01/2010 09:20"/>

    </Photos>
</Album>
</Albums>

The best I've come up with is 我想出的最好的是

 XDocument xmlDoc = XDocument.Load(GalleryFilePath);
                 var x = from c in xmlDoc.Descendants("Album")
                    where int.Parse(c.Attribute("GalleryId").Value) == GalleryId
                    orderby c.Attribute("Title").Value descending
                    select new
                    {
                        Title = c.Element("Photos").Element("Photo").Attribute("Title").Value,
                        URL = c.Element("Photos").Element("Photo").Attribute("URL").Value,
                        DateAdded = c.Element("Photos").Element("Photo").Attribute("DateAdded").Value
                    };

This returns nothing, I'm guessing this is because I'm telling it to query the Album element then trying to loop through the photo elements. 什么都不返回,我猜这是因为我告诉它查询Album元素然后尝试遍历照片元素。 Any tips as to how this should be done? 关于如何做到这一点的任何提示?

Thanks 谢谢

Edit : Code updated to reflect answers 编辑:更新代码以反映答案

It's a common mistake to confuse the Attribute object with a value. Attribute对象与值混淆是一个常见的错误。 You should use Attribute("x").Value to retrieve it's value. 您应该使用Attribute("x").Value来检索它的值。

Try this corrected code: 试试这个更正的代码:

XDocument xmlDoc = XDocument.Load(GalleryFilePath);
var x = from c in xmlDoc.Descendants("Photo")
        where c.Parent.Parent.Attribute("GalleryId").Value.Equals(GalleryId)
        orderby c.Parent.Parent.Attribute("Title").Value descending
        select new
        {
            Title = c.Attribute("Title").Value,
            URL = c.Attribute("URL").Value,
            DateAdded = c.Attribute("DateAdded").Value
        };

[Update] To retrieve a list of photo's, I've set the from to the photo elements, and the where to the album, which is 2 levels up in the provided sample XML. [更新]要检索照片列表,我将照片元素设置为照片元素,以及相册的位置,在提供的示例XML中为2级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM