c# - 编写 Linq2Xml 查询时出现问题

标签 c# linq-to-xml

我正在尝试编写 Linq2XML 查询来查询以下 XML。我需要它来拉回给定 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>

我想到的最好的是

 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
                    };

这没有返回任何内容,我猜这是因为我告诉它查询 Album 元素然后尝试遍历照片元素。有关如何完成此操作的任何提示?

谢谢

编辑:更新代码以反射(reflect)答案

最佳答案

Attribute 对象与值混淆是一个常见的错误。您应该使用 Attribute("x").Value 来检索它的值。

试试这个更正后的代码:

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
        };

[更新] 为了检索照片列表,我将 from 设置为 photo 元素,并将 where 设置为相册,这在提供的示例 XML 中向上 2 层。

关于c# - 编写 Linq2Xml 查询时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2653076/

相关文章:

c# - 一个类轮,如果呼吁采取行动

c# - 使用 C# 的新异步功能等待网络数据包的最佳方式是什么

c# - 在此处获取 XElement 的行号

c# - LINQ to XML 新手问题 : Returning More Than One Result

c# - 如何访问子 xml 元素?

c# - Parallel.ForEach 显然是克隆引用类型?

c# - 如何在枚举和 int 上使用按位或?

c# - 设置数据库模式名称而不设置表名称

c# - 如果子节点元素相等,如何添加父节点?

c# - 针对多个模式验证未知 xml,直到找到匹配项