2010-04-16 52 views
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 
        }; 

這沒有返回,我猜這是因爲我告訴它來查詢專輯元素,然後通過努力環照片元素。有關如何完成此任務的任何提示?

感謝

編輯:代碼更新,以反映答案

回答

3

這是一個常見的錯誤是用一個值混淆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 
     }; 

[更新]要檢索照片的清單,我已經設置了從該照片的元素,而其中的專輯,這是2級在提供的示例XML中。

+0

好的,謝謝,我更新了代碼以使用屬性的值。但是,當我調用ToList或Count時,查詢現在會拋出空引用異常。 – Gavin 2010-04-16 13:08:52

+0

@Gavin在你的真實數據中,所有'Album'節點都具有所提及的屬性?所有'Photo'節點都有三個屬性嗎?如果不是,'Attribute(name)'將爲空,當你調用'.Value'時會出現異常。 – AakashM 2010-04-16 13:15:18

+0

在這種情況下,使用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