【发布时间】:2018-04-17 17:56:27
【问题描述】:
有一个 XML 文件:
<favorites>
<movies>
<movie title="The Godfather" year="1974" />
<movie title="The Terminator" year="1984" />
<movie title="Dark Knight" year="2008" />
</movies>
<books>
<book title = "1984" author="George Orwell" />
<book title = "Robinson Crusoe"" author="Daniel Defoe"/>
<book title = "Frankenstein" author="Mary Shelly" />
</books>
<music>
<artist title = "Beatles" genre="rock" />
<artist title = "Queen" genre="rock" />
<artist title = "Metallica" rock="heavy metal" />
</music>
</favorites>
我需要过滤一个特定的节点(音乐)所有的父子节点。 结果应该是:
<favorites>
<music>
<artist title="Beatles" genre="rock" />
<artist title="Queen" genre="rock" />
<artist title="Metallica" rock="heavy metal" />
</music>
</favorites>
我找到了使用 System.XML 和 LINQ 过滤 XML 的解决方案:
XDocument xdoc = XDocument.Parse(xmlString);
xdoc.Descendants()
.Where(x => x.Name != "favorites" & x.Name != "music" & x.Name != "artist")
.Remove();
Console.WriteLine(xdoc.ToString());
工作示例在这里:https://dotnetfiddle.net/NnA4h7#
问题是我必须在查询中指定所有父节点和子节点。
有没有办法只指定一个想要的节点(电影、书籍、音乐)来获得相同的结果?
【问题讨论】: