簡體   English   中英

如何按屬性對XDocument進行排序?

[英]How can I sort an XDocument by attribute?

我有一些XML

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

我想按名字排序。 我使用XDocument加載該xml。 如何查看按名稱排序的xml?

如果不是XmlDocument,您可以使用LINQ to Xml進行排序

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM