...">

Sorting XElement Attributes

I have an XML file like this:

<Users>
    <User>
        <Adress Name="bbbb"/>
        <Adress Name="aaaa" />
    </User>
</Users>

      

I want to sort the element nodes User

in ascending order. How can I arrange the items Adress

?

Thank you for your help.

+2


a source to share


2 answers


If node is your node user:



node.Elements("Adress").OrderBy(e=>e.Attribute("Name").Value)

      

+8


a source


Do you just want to work with XML objects in memory, or do you want to store the sorted results in a file?

This code shows you how to reorder the elements in the XDocument so you can keep it.

string xml = @"<Users> 
<User> 
<Address Name=""bbbb""/> 
<Address Name=""aaaa"" /> 
</User> 
<User> 
<Address Name=""dddd""/> 
<Address Name=""cccc"" /> 
</User> 
</Users> ";

XDocument document = XDocument.Parse(xml);

var users = document.Root.Elements("User");
foreach (var user in users)
{
    var elements = user.Elements("Address").OrderBy(a => a.Attribute("Name").Value).ToArray();
    user.Elements().Remove();
    user.Add(elements);
}

      



If you want an ordered in memory model, then you can do it like

var query = from user in document.Root.Elements("User")
            select new
            {
                Addresses = from address in user.Elements("Address")
                            orderby address.Attribute("Name").Value
                            select new
                            {
                                Name = address.Attribute("Name").Value 
                            }
            };

foreach (var user in query)
{
    foreach (var address in user.Addresses)
    {
        // do something with address.Name
    }
}

      

+3


a source







All Articles