使用 C# 按属性对 XmlDocument 进行排序

Sort XmlDocument by attribute using C#

我有一个看起来像这样的 XmlDocument;

<Root>
  <file id="1" amount="10" att="0" />
  <file id="2" amount="20" att="0"/>
  <file id="3" amount="40" att="0"/>
  <file id="4" amount="30" att="0"/>
  <file id="5" amount="10" att="0"/>
</Root>

排序后应该是这样的:

<Root>
  <file id="3" amount="40" att="0"/>
  <file id="4" amount="30" att="0"/>
  <file id="2" amount="20" att="0"/>
  <file id="1" amount="10" att="0"/>
  <file id="5" amount="10" att="0"/>
</Root>

我生成一个 XmlDocument;

XmlDocument xDoc = new XmlDocument();

然后我生成一个 XmlNodeList;

XmlNodeList xAmount = xDoc.SelectNodes("Root/file[@att='0']");

然后我执行一个 for 循环并构建一个多维数组。

amtArray = new int[xAmount.Count, 2];

for (int i = 0; i < xAmount.Count; i++)
{
    amtArray[i,0] = xAmount[i].Attribute["id"].Value;
    amtArray[i,1] = xAmount[i].Attribute["amount"].Value;
}

我可以在可能的任何给定点尝试排序。

对整个XmlDocument、xDoc进行排序

对 XmlNodeList 进行排序,xAmount

对多维数组进行排序。

我在问是否有办法对整个 XmlDocument 或 XmlNodeList 进行排序。

我发现 Linq2Xml 更容易使用..

var xDoc = XDocument.Load(filename);
var newxDoc = new XElement("Root", xDoc.Root
                                   .Elements()
                                   .OrderByDescending(x => (int)x.Attribute("amount"))
                                   .ThenBy(x=>(int)x.Attribute("id"))
                            );
string xml = newxDoc.ToString();

输出:

<Root>
  <file id="3" amount="40" att="0" />
  <file id="4" amount="30" att="0" />
  <file id="2" amount="20" att="0" />
  <file id="1" amount="10" att="0" />
  <file id="5" amount="10" att="0" />
</Root>