如何获取所有流派的列表? 现在我只得到每首歌的第一个流派。
XML 文件:
<Library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Songs>
<Song>
<Title>High Hopes</Title>
<Genres>
<Genre>Rock</Genre>
<Genre>American</Genre>
</Genres>
</Song>
<Song>
<Title>Imagine</Title>
<Genres>
<Genre>Pop</Genre>
<Genre>Unplugged</Genre>
</Genres>
</Song>
</Songs>
</Library>
C# 代码:
public void ListGenres()
{
System.Xml.Linq.XElement xLibrary = System.Xml.Linq.XElement.Load(@"c:\Library.xml");
System.Xml.Linq.XElement xSongs = xLibrary.Element("Songs");
System.Collections.Generic.IEnumerable<string> genres =
from code in xSongs.Elements("Song")
let genre = (string)code.Element("Genres").Element("Genre")
orderby genre
select genre;
foreach (string genre in genres)
{
Console.WriteLine(genre);
}
}
结果:
Pop
Rock
但我需要:
Rock
American
Pop
Unplugged
谢谢。
最佳答案
由于您没有执行任何过滤器,因此您可以直接使用后代
,如下所示:-
XDocument xLibrary = XDocument.Load(@"c:\Library.xml");
IEnumerable<string> result = xLibrary.Descendants("Genre").Select(x => (string)x);
或者如果您更喜欢查询语法:-
IEnumerable<string> res = from genre in xdoc.Descendants("Genre")
select (string)genre;
您需要为此导入using System.Linq;
。这将产生您期望的输出,即Rock American Pop Unplugged,即使它没有订购。您始终可以使用 order by
caluse 来实现此目的。
检查this回答以理解为什么我使用后代
而不是元素
。
关于c# - 如何使用 Linq to XML 获取数组的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32881941/