XElement attribute sorting

ε祈祈猫儿з 提交于 2019-12-10 23:39:17

问题


I have a XML file like that:

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

I want to sort User element's nodes in ascending order. How can I order Adress elements?

Thank you for your help.


回答1:


If node is your user node:

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



回答2:


Are you merely wanting to work with the XML objects in memory or are you looking to store the sorted results back in a file?

This code shows reordering the elements within an XDocument so that you can save 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 this

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
    }
}


来源:https://stackoverflow.com/questions/2699452/xelement-attribute-sorting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!