2010-12-04 6 views
1

미리 감사드립니다. 이것은 아주 좋은 자료입니다.Linq to 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> 

:

이것은 XML입니다


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

우수 .... 감사합니다. –

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

흥미 롭군요! 작동하면 더 매끄럽게 보입니다. –