开发者

How can I sort an XDocument by attribute?

开发者 https://www.devze.com 2022-12-19 21:18 出处:网络
I have some XML <Users> <User Name=\"Z\"/> <User Name=\"D\"/> <User Name=\"A\"/> </User>

I have some XML

<Users>
    <User Name="Z"/>
    <User Name="D"/>
    <User Name="A"/>
</User>

I want to sort that by Name. I load that xml using XDoc开发者_高级运维ument. How can I view that xml sorted by Name?


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));


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

精彩评论

暂无评论...
验证码 换一张
取 消