Sorting all the elements in a XDocument

前端 未结 4 626
孤城傲影
孤城傲影 2020-12-10 02:56

I have a XDocument where I\'d like to sort all of the elements alphabetically. Here\'s a simplified version of the structure:


 
         


        
4条回答
  •  孤街浪徒
    2020-12-10 03:12

    Here is an updated example that will include all attributes when performing the sort.

    private static XElement Sort(XElement element)
    {
        XElement newElement = new XElement(element.Name,
            from child in element.Elements()
            orderby child.Name.ToString()
            select Sort(child));
        if (element.HasAttributes)
        {
            foreach (XAttribute attrib in element.Attributes())
            {
                newElement.SetAttributeValue(attrib.Name, attrib.Value);
            }
        }
        return newElement;
    }
    
    private static XDocument Sort(XDocument file)
    {
        return new XDocument(Sort(file.Root));
    }
    

    This post helped me a lot, because I did not want to perform an XML sort using XSLT since I did not want to reformat the XML. I searched all around for a simple solution to perform an XML sort using C# and ASP.NET and I was delighted when I found this thread. Thanks to all, this did exactly what I needed.

提交回复
热议问题