c# - 如何使用 Linq to XML 获取数组的数组?

标签 c# arrays xml linq-to-xml xelement

如何获取所有流派的列表? 现在我只得到每首歌的第一个流派。

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/

相关文章:

c# - 默认代理如何绕过大多数网址并仅适用于少数

c# - 如何在 C# 中复制数组

c# - 如何使用 TDD 方法创建 Restful Web 服务?

c# - 嵌套列表 C# 的 XML 反序列化

c# - Quartz.Net 作业在几次异常后停止触发

java - 使用杂耍算法进行数组旋转失败

javascript - 无法对二维数组的每个数组进行排序

javascript - 在Javascript中从多维数组中删除元素

python - 为 datex2 到 Pandas Dataframe 的转换创建 XSLT 文件

java - XSL 转换,然后在结果节点上进行 XPath 表达式