在 C# 中,按字母順序對 XML 檔案進行排序的最佳方法是什么——元素和屬性都包括在內?例如,如果我從 b.xml 開始,它應該變成 a.xml:

現在,我正在考慮遞回遍歷所有元素,對于每個元素,我將洗掉其子元素,然后按字母順序再次添加它們,并對屬性執行相同操作。
這是我應該采取的方法還是有更好的方法或現成的功能?
uj5u.com熱心網友回復:
好的,經過一些試驗,我想出了一個適用于我的測驗檔案的函式。
private static void SortXml(XmlElement node)
{
// Load the child elements into a collection.
List<XmlElement> childElements = new();
foreach (XmlElement childNode in node.ChildNodes)
{
childElements.Add(childNode);
// Call recursively if the child is not a leaf.
if (childNode.HasChildNodes)
{
SortXml(childNode);
}
}
// Load the attributes into a collection.
List<XmlAttribute> attributes = new();
foreach (XmlAttribute attrib in node.Attributes)
{
attributes.Add(attrib);
}
node.RemoveAll();
// Re-add the child elements (sorted).
foreach (var childNode in childElements.OrderBy(element => element.Name))
{
node.AppendChild(childNode);
}
// Re-add the attributes (sorted).
foreach (var childNode in attributes.OrderBy(attrib => attrib.Name))
{
node.Attributes.Append(childNode);
}
}
稍后我將對其進行更徹底的測驗。
uj5u.com熱心網友回復:
嗨@Sashoalm 這個解決方案可能對你有幫助。
class Program
{
static void Main(string[] args)
{
string xml = @"<?xml version=""1.0"" encoding=""UTF-8\""?>
<websites>
<site language=""Spanish"" name=""Excélsior"" order=""2"">http://www.excelsior.com.mx/</site>
<site language=""Japanese"" name=""TOKYO Web""
order=""3"">http://www.tokyo-np.co.jp/</site>
<site language=""Italian"" name=""Corriere della Sera""
order=""1"">http://www.corriere.it/</site>
<site language=""Spanish"" name=""SpanishTest1"" order=""4"">www.spanishtest1.com</site>
</websites>";
XDocument xdoc = XDocument.Parse(xml);
XDocument xNewDoc = new XDocument();
xNewDoc.Add(xdoc.Root);
xNewDoc.Root.RemoveNodes();
xNewDoc.Root.Add(xdoc.Root.Elements().OrderBy(e => e.Attribute("language").Value));
Console.WriteLine("Before: \r\n{0}", xdoc.ToString());
Console.WriteLine();
Console.WriteLine("After: \r\n{0}", xNewDoc.ToString());
Console.ReadLine();
}
-
1. List item
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/369174.html
