简体   繁体   English

使用XDocument更改XML的顺序

[英]Change order of XML using XDocument

I want to change the order of XML using XDocument 我想使用XDocument更改XML的顺序

<root>
  <one>1</one>
  <two>2</two>
</root>

I want to change the order so that 2 appears before 1. Is this capability baked in or do I have to do it myself. 我想更改顺序,以便2出现在1之前。这个功能是否已经完成,或者我必须自己完成。 For example, remove then AddBeforeSelf()? 例如,删除AddBeforeSelf()?

Thanks 谢谢

Similar to above, but wrapping it in an extension method. 与上面类似,但将其包装在扩展方法中。 In my case this works fine for me as I just want to ensure a certain element order is applied in my document before the user saves the xml. 在我的情况下,这对我来说很好,因为我只想确保在用户保存xml之前在我的文档中应用某个元素顺序。

public static class XElementExtensions
{
    public static void OrderElements(this XElement parent, params string[] orderedLocalNames)
    {            
        List<string> order = new List<string>(orderedLocalNames);            
        var orderedNodes = parent.Elements().OrderBy(e => order.IndexOf(e.Name.LocalName) >= 0? order.IndexOf(e.Name.LocalName): Int32.MaxValue);
        parent.ReplaceNodes(orderedNodes);
    }
}
// using the extension method before persisting xml
this.Root.Element("parentNode").OrderElements("one", "two", "three", "four");

This should do the trick. 这应该可以解决问题。 It order the child nodes of the root based on their content and then changes their order in the document. 它根据内容的顺序对根节点的子节点进行排序,然后在文档中更改它们的顺序。 This is likely not the most effective way but judging by your tags you wanted to see it with LINQ. 这可能不是最有效的方法,但是根据你想用LINQ看到它的标签判断。

static void Main(string[] args)
{
    XDocument doc = new XDocument(
        new XElement("root",
            new XElement("one", 1),
            new XElement("two", 2)
            ));

    var results = from XElement el in doc.Element("root").Descendants()
                  orderby el.Value descending
                  select el;

    foreach (var item in results)
        Console.WriteLine(item);

    doc.Root.ReplaceAll( results.ToArray());

    Console.WriteLine(doc);

    Console.ReadKey();
}

在编写C#代码之外,您可以使用XSLT转换XML。

Try this solution... 尝试此解决方案......

XElement node = ...get the element...

//Move up
if (node.PreviousNode != null) {
    node.PreviousNode.AddBeforeSelf(node);
    node.Remove();
}

//Move down
if (node.NextNode != null) {
    node.NextNode.AddAfterSelf(node);
    node.Remove();
}

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

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