使用XDocument更改XML的顺序

B2.*_*B2. 8 .net c# linq linq-to-xml

我想使用XDocument更改XML的顺序

<root>
  <one>1</one>
  <two>2</two>
</root>
Run Code Online (Sandbox Code Playgroud)

我想更改顺序,以便2出现在1之前.这个功能是否已经完成,或者我必须自己完成.例如,删除AddBeforeSelf()?

谢谢

小智 5

与上述类似,但将其包装在扩展方法中。就我而言,这对我来说很好,因为我只想确保在用户保存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");
Run Code Online (Sandbox Code Playgroud)


sma*_*ell 1

这应该可以解决问题。它根据根的子节点的内容对它们进行排序,然后更改它们在文档中的顺序。这可能不是最有效的方法,但根据您的标签判断,您希望使用 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();
}
Run Code Online (Sandbox Code Playgroud)