3
我想寫一個Linq2XML查詢來查詢下面的XML。我需要它將所有照片退回給定的GalleryID。問題編寫Linq2Xml查詢
<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
};
這沒有返回,我猜這是因爲我告訴它來查詢專輯元素,然後通過努力環照片元素。有關如何完成此任務的任何提示?
感謝
編輯:代碼更新,以反映答案
好的,謝謝,我更新了代碼以使用屬性的值。但是,當我調用ToList或Count時,查詢現在會拋出空引用異常。 – Gavin 2010-04-16 13:08:52
@Gavin在你的真實數據中,所有'Album'節點都具有所提及的屬性?所有'Photo'節點都有三個屬性嗎?如果不是,'Attribute(name)'將爲空,當你調用'.Value'時會出現異常。 – AakashM 2010-04-16 13:15:18
在這種情況下,使用Jon Skeet的擴展方法:http://stackoverflow.com/questions/792919/how-do-you -guard-for-null-reference-exceptions-in-linq-to-xml/792945#792945 – Prutswonder 2010-04-16 13:21:31