Linq to XML:我无法比较嵌套元素

时间:2010-12-04 21:59:14

标签: c# xml linq

提前感谢您,这是一个很好的资源。

我相信代码解释了自己,但为了防止我傲慢,我会解释自己。

我的节目根据所选类型的下拉列表将电影列入树视图。每部电影都有一些类型,比如嵌套的流派。

这是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 个答案:

答案 0 :(得分: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节点,所以你必须检查它们是否匹配而不是第一个。

答案 1 :(得分:0)

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