【问题标题】:How can I sort an XDocument by attribute?如何按属性对 XDocument 进行排序?
【发布时间】:2011-01-14 23:34:22
【问题描述】:

我有一些 XML

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

我想按 Name 对其进行排序。我使用XDocument 加载该xml。如何查看按名称排序的 xml?

【问题讨论】:

    标签: c# sorting linq-to-xml


    【解决方案1】:

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

    【讨论】:

    • 我这样做了,但我有一个例外。 “至少一个对象必须实现 IComparable”。
    • 必须是node.Attribute("Name").Value
    • 仅供参考,如果缺少该属性,则直接执行node.Attribute("Name").Value 会使您打开空引用异常。此外,如果 XML 文档指定了一个模式,那么仅仅使用 node.Attribute("Name") 也是不够的,因为您必须使用正确的 XName 来查找属性。
    【解决方案2】:
    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));
    

    【讨论】:

    • 名称是一个属性,而不是一个元素;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多