我正在尝试使用Linq对XML进行排序,但它不起作用这是XML
<hierarchy>
<date>2015/04/01 15:29:10</date>
<folder name="Root" id="Root">
<file id="Fukui_R3_20150327182224.xlsx" />
<file id="BordersTest_20150330144902.xlsx" />
<folder name="level-1" id="1427455995512">
<file id="Fukui_R3_20150327182224.xlsx" />
<file id="BordersTest_20150330144902.xlsx" />
<folder name="Zxcf" id="1427869724768">
<file id="Fukui_R3_20150327182224.xlsx" />
<file id="BordersTest_20150330144902.xlsx" />
</folder>
<folder name="Aegh" id="1427869732372">
<file id="Fukui_R3_20150327182224.xlsx" />
<file id="BordersTest_20150330144902.xlsx" />
</folder>
<folder name="Cfgt" id="1427869741718" />
</folder>
<folder name="A-level" id="1427869672074" />
<folder name="G-Level" id="1427869682304" />
<folder name="E-Level" id="1427869690384" />
<folder name="1-A-Level" id="1427869701383" />
</folder>
</hierarchy>
这是我试过的代码
XDocument xDoc = XDocument.Load(FilePath);
foreach (var trans in xDoc.Descendants("hierarchy"))
{
trans.ReplaceAll( trans.Elements().OrderBy(x=>x.Name.LocalName));
}
string newXml = xDoc.ToString();
但是它返回了同样未排序的XML。
答案 0 :(得分:3)
重写你的代码:
XDocument xDoc = XDocument.Load(FilePath);
if (xDoc.Root != null)
SortXml(xDoc.Root);
string newXml = xDoc.ToString();
并尝试使用此方法:
private static void SortXml(XContainer parent)
{
var elements = parent.Elements()
.OrderByDescending(e => e.Name.LocalName)
.ThenBy(e => (string)e.Attribute("name"))
.ToArray();
Array.ForEach(elements, e => e.Remove());
foreach (var element in elements) {
parent.Add(element);
SortXml(element);
}
}
此代码以递归方式对层次结构进行排序:文件始终位于文件夹之后,所有项目均按属性“name”的值排序。