How can I sort an XDocument by attribute?

后端 未结 2 1537
一个人的身影
一个人的身影 2020-12-11 15:47

I have some XML


    
    
    

I want t

相关标签:
2条回答
  • 2020-12-11 16:05
    XDocument xdoc = new XDocument(
        new XElement("Users",
            new XElement("Name", "Z"),
            new XElement("Name", "D"),
            new XElement("Name", "A")));
    
    var doc = xdoc.Element("Users").Elements("Name").OrderBy(n => n.Value);
    XDocument doc2 = new XDocument(new XElement("Users", doc));
    
    0 讨论(0)
  • 2020-12-11 16:17

    You can sort using LINQ to Xml, if XmlDocument is not the case

    XDocument input = XDocument.Load(@"input.xml");
    XDocument output = new XDocument(
        new XElement("Users",
            from node in input.Root.Elements()
            orderby node.Attribute("Name").Value descending
            select node));
    
    0 讨论(0)
提交回复
热议问题