如何使用XDocument读取多个嵌入元素

本文关键字:元素 何使用 XDocument 读取 | 更新日期: 2023-09-27 18:01:51

这是我正在阅读的XML文件的一部分:

<?xml version="1.0"?>
<movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ThumbGen="1">
  <hasrighttoleftdirection>false</hasrighttoleftdirection>
  <title>A Nightmare on Elm Street</title>
  <originaltitle>A Nightmare on Elm Street</originaltitle>
  <year>1984</year>
  <plot>Years after being burned alive by a mob of angry parents, child murderer Freddy Krueger returns to haunt the dreams -- and reality -- of local teenagers. As the town's teens begin dropping like flies, Nancy and her boyfriend, Glen, devise a plan to lure the monster out of the realm of nightmares and into the real world.</plot>
  <tagline>A scream that wakes you up, might be your own...</tagline>
  <metascore>78</metascore>
  <trailer>http://www.youtube.com/watch?v=996</trailer>
  <rating>8.6</rating>
  <episodes />
  <episodesnames />
  <writers />
  <gueststars />
  <id>tt0087800</id>
  <releasedate>11.09.1984</releasedate>
  <actor>
    <name>Robert Englund</name>
    <name>Heather Langenkamp</name>
    <name>Johnny Depp</name>
    <name>Ronee Blakley</name>
    <name>John Saxon</name>
    <name>Amanda Wyss</name>
    <name>Jsu Garcia</name>
    <name>Charles Fleischer</name>
    <name>Joseph Whipp</name>
    <name>Lin Shaye</name>
    <name>Joe Unger</name>
    <name>Mimi Craven</name>
    <name>David Andrews</name>
  </actor>
  <genre>
    <name>Horror</name>
    <name>Comedy</name>
  </genre>
  <director>
    <name>Wes Craven</name>
  </director>
  <runtime>91</runtime>
  <certification>R</certification>
  <studio>
    <name>New Line Cinema</name>
  </studio>
  <country>
    <name>United States of America</name>
  </country>
  ...
  ...
  ...
</movie>

感谢Henk Holterman,我能够清理处理XML的代码,现在我使用以下代码:

var doc = XDocument.Load(n);  // takes care of all Open/Close issues
strTitle = doc.Root.Element("title") == null ? "" : doc.Root.Element("title").Value;
strYear = doc.Root.Element("year") == null ? "" : doc.Root.Element("year").Value;
strPlot = doc.Root.Element("plot") == null ? "" : doc.Root.Element("plot").Value;
strRating = doc.Root.Element("rating") == null ? "" : doc.Root.Element("rating").Value;
strMPAA = doc.Root.Element("mpaa") == null ? "" : doc.Root.Element("mpaa").Value;
strCertification = doc.Root.Element("certification") == null ? "" : doc.Root.Element("certification").Value;

现在是最后一点,我如何使用这种方法从genre元素中获得genre ?我无法搜索名称Element,因为它在各种其他元素中使用。我不确定我是否能处理:

doc.Root.Element("genre").ElementsAfterSelf("name");

不清楚返回的是什么(我不太明白如何使用IEnumberables),或者它如何处理多个"名称"。我想这可以用LINQ来完成,但我仍在试图弄清楚如何使用它。

非常感谢!

如何使用XDocument读取多个嵌入元素

你可以得到一个类型列表:

// untested
List<string> genres = doc.Root
      .Element("genre")
      .Elements("name")
      .Select(x => x.Value).ToList();