2010-12-04 1 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