简体   繁体   English

如何对 xml 个节点进行排序

[英]how to sort xml nodes

I have an XML file in which I want to sort the Object nodes alphabetically and write them back to the file.我有一个 XML 文件,我想在其中按字母顺序对 Object 节点进行排序并将它们写回到文件中。 The raw file looks like this:原始文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Package>
  <Objects>
    <Object Type="Package">moB</Object>
    <Object Type="Package">moA</Object>
    <Object Type="Package">moC</Object>
  </Objects>
</Package>

The expected output should be:预期的 output 应该是:

<?xml version="1.0" encoding="utf-8"?>
<Package>
  <Objects>
    <Object Type="Package">moA</Object>
    <Object Type="Package">moB</Object>
    <Object Type="Package">moC</Object>
  </Objects>
</Package>

I want to solve this with LINQ, unfortunately I can't get the query to read the "Object" nodes as a collection for further processing.我想用 LINQ 解决这个问题,不幸的是我无法获取查询以将“对象”节点读取为一个集合以供进一步处理。

var xdoc = XDocument.Load(inputFile);
var orderedList = xdoc.Root.Element("Objects");

Try with this line, in order to select the Objects elements and order them:尝试使用这一行,以便 select 对象元素并对其进行排序:

var orderedList = xdoc.Root.Element("Objects")
                      .Elements("Object")
                      .OrderBy(e => e.Value);

Then you should create a new xElement to hold the sorted object elements and replace the original with the sorted version, and just save the modified doc!然后你应该创建一个新的 xElement 来保存排序后的 object 个元素,并将原始元素替换为排序后的版本,并保存修改后的文档!

I want to solve this with LINQ, unfortunately I can't get the query to read the "Object" nodes as a collection for further processing.我想用 LINQ 解决这个问题,不幸的是我无法获取查询以将“对象”节点读取为一个集合以供进一步处理。

You are only reading the root Objects , you need to read all the inner Object nodes:您只读取根Objects ,您需要读取所有内部Object节点:

var objectList = xdoc.Root.Element("Objects").Elements("Object");

You can then sort them by inner text:然后您可以按内部文本对它们进行排序:

var orderedList = objectList.OrderBy(x => x.Value); 

And replace the old Object nodes by the ordered ones:并用有序节点替换旧的Object节点:

xdoc.Root.Element("Objects").ReplaceNodes(orderedList);

Finally you can save them back to the file:最后你可以将它们保存回文件中:

xdoc.Save(inputFile); // save

If you want to keep the original, I'd suggest saving it to a different file:如果您想保留原件,我建议将其保存到不同的文件中:

xdoc.Save("someOtherFile.xml"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM