如何在 C# 中按节点属性对 XML 文件进行排序

2023-12-27

不要求任何人为我编写这个解决方案 - 只是寻找最佳方法的指导。我正在 VS2015 中使用 C# 代码处理一个 .aspx 文件。

我发现无数线程解释如何对 XML 文件中的节点进行排序。但是,我还没有找到任何关于如何根据公共子节点属性对具有相同结构的多个 XML 文件进行排序的线程。

我的情况:我有一个包含数百个 XML 文件的目录,简单地命名为 0001.xml 到 6400.xml。每个 XML 文件都具有相同的结构。我想根据子节点的属性对文件(而不是节点)进行排序。

每个 XML 文件都有一个“项目”父节点,并具有“年份”、“语言”和“作者”等子节点。例如:

<item id="0001">
   <year>2011</year>
   <language id="English" />
   <author sortby="Smith">John F. Smith</author>
   <content></content>
</item>

如果我不想按照 0001 到 6400 的顺序列出文件,而是想根据 item/author 节点的 @sortby 属性按字母顺序列出它们,我该怎么做?

我的一个想法是创建一个临时 XML 文件,从每个 XML 文件中收集所需的信息。然后,我可以对临时 XML 文件进行排序,然后循环遍历节点以按正确的顺序显示文件。像这样的东西...

XDocument tempXML = new XDocument();
// add parent node of <items>

string[] items = Directory.GetFiles(directory)
foreach (string item in items)
{
   // add child node of <item> with attributes "filename", "year", "language", and "author"
}

// then sort the XML nodes according to attributes

这有道理吗?有没有更聪明的方法来做到这一点?


Sorting

我们可以使用一些 LINQ to Xml 显示排序的 xml 文件,代码如下:

var xmlsWithFileName = Directory.GetFiles(directory)
                                .Select(fileName => new { fileName, xml = XDocument.Parse(File.ReadAllText(fileName)) })
                                .OrderBy(tuple => tuple.xml.Element("item").Element("author").Attribute("sortby").Value);

的每个元素带文件名的 xml将会有

  • xml 属性,包含 XDocument 中的 XML
  • fileName 属性,包含 XML 文件的路径

假设您的目标目录中有以下 xml 文件:

0001.xml

<item id="0001">
   <year>2011</year>
   <language id="English" />
   <author sortby="Smith">John F.Smith</author>
   <content></content>
</item>

0002.xml

<item id="0002">
   <year>2012</year>
   <language id="Portuguese" />
   <author sortby="Monteiro">Alberto Monteiro</author>
   <content></content>
</item>

您可以使用此代码来测试

public static void ShowXmlOrderedBySortByAttribute(string directory)
{
    var xmlsWithFileName = Directory.GetFiles(directory)
                                    .Select(fileName => new { fileName, xml = XDocument.Parse(File.ReadAllText(fileName)) })
                                    .OrderBy(tuple => tuple.xml.Element("item").Element("author").Attribute("sortby").Value);

    foreach (var xml in xmlsWithFileName)
    {
        Console.WriteLine($"Filename: {xml.fileName}{Environment.NewLine}Xml content:{Environment.NewLine}");
        Console.WriteLine(xml.xml.ToString());
        Console.WriteLine("================");
    }
}

这段代码的输出是:

Filename: c:\temp\teste\0002.xml
Xml content:

<item id="0002">
  <year>2012</year>
  <language id="Portuguese" />
  <author sortby="Monteiro">Alberto Monteiro</author>
  <content></content>
</item>
================
Filename: c:\temp\teste\0001.xml
Xml content:

<item id="0001">
  <year>2011</year>
  <language id="English" />
  <author sortby="Smith">John F.Smith</author>
  <content></content>
</item>
================

如您所见,XML 0002.xml 出现在第一位,然后是 0001.xml

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 C# 中按节点属性对 XML 文件进行排序 的相关文章

随机推荐