编写Linq2Xml查询问题
作者:互联网
我正在尝试编写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元素,然后尝试遍历photo元素.关于应该如何做的任何提示?
谢谢
编辑:更新代码以反映答案
解决方法:
将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元素,将from设置为相册的位置,在提供的示例XML中,相册的位置增加了2级.
标签:linq-to-xml,c 来源: https://codeday.me/bug/20191210/2099418.html