2010-12-04 37 views
1

預先感謝您,這是一個很好的資源。Linq to XML:我無法比較嵌套元素

我相信代碼解釋本身,但爲了以防萬一,我傲慢,我會解釋一下。

我的程序根據下拉列表中選擇的流派列出了電影,樹形視圖。每部電影都有幾種流派,不同的流派。

這是XML:

<movie> 
    <title>2012</title> 
    <director>Roland Emmerich</director> 
    <writtenBy> 
     <writter>Roland Emmerich,</writter> 
     <writter>Harald Kloser</writter> 
    </writtenBy> 
    <releaseDate>12-Nov-2009</releaseDate> 
    <actors> 
     <actor>John Cusack,</actor> 
     <actor>Thandie Newton, </actor> 
     <actor>Chiwetel Ejiofor</actor> 
    </actors> 
    <filePath>H:\2012\2012.avi</filePath> 
    <picPath>~\image\2012.jpg</picPath> 
    <runningTime>158 min</runningTime> 
    <plot>Dr. Adrian Helmsley, part of a worldwide geophysical team investigating the effect on the earth of radiation from unprecedented solar storms, learns that the earth's core is heating up. He warns U.S. President Thomas Wilson that the crust of the earth is becoming unstable and that without proper preparations for saving a fraction of the world's population, the entire race is doomed. Meanwhile, writer Jackson Curtis stumbles on the same information. While the world's leaders race to build "arks" to escape the impending cataclysm, Curtis struggles to find a way to save his family. Meanwhile, volcanic eruptions and earthquakes of unprecedented strength wreak havoc around the world. </plot> 
    <trailer>http://2012-movie-trailer.blogspot.com/</trailer> 
    <genres> 
     <genre>Action</genre> 
     <genre>Adventure</genre> 
     <genre>Drama</genre> 
    </genres> 
    <rated>PG-13</rated> 
</movie> 

這是代碼:


string selectedGenre = this.ddlGenre.SelectedItem.ToString(); 
      XDocument xmldoc = XDocument.Load(Server.MapPath("~/App_Data/movie.xml")); 

List<Movie> movies = 
       (from movie in xmldoc.Descendants("movie") 
       // The treeView doesn't exist 
       where movie.Elements("genres").Elements("genre").ToString() == selectedGenre 

    select new Movie 
       { 
        Title = movie.Element("title").Value 
       }).ToList(); 

    foreach (var movie in movies) 
       { 
        TreeNode myNode = new TreeNode(); 
        myNode.Text = movie.Title; 
        TreeView1.Nodes.Add(myNode); 
       } 

回答

2

更改您的代碼

List<Movie> movies = 
       (from movie in xmldoc.Descendants("movie") 
       where movie.Elements("genres").Elements("genre").Any(e => e.Value == selectedGenre) 

       select new Movie 
       { 
        Title = movie.Element("title").Value 
       }).ToList(); 

這是因爲有超過1 genre節點,所以你必須檢查它們中的任何一個是否匹配而不是第一個匹配。

+0

非常好....謝謝 – 2010-12-04 23:46:19

0
List<Movie> movies = 
       (from movie in xmldoc.Descendants("movie") 
       where movie.Elements("genres") 
       .Any((e) => e.Elements("genre").ToString() == selectedGenre); 
+0

有趣的我也會試試這個!如果它工作,它看起來更時尚 – 2010-12-23 13:35:20