我正在尝试编写 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/