如何按属性对XDocument进行排序?

13

我有一些XML

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

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

2个回答

15

如果不使用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接口"。 - cagin
它需要是 node.Attribute("Name").Value - Daniel Schaffer
顺便提一下,如果缺少该属性,则直接使用 node.Attribute("Name").Value 会导致空引用异常。此外,如果 XML 文档指定了模式,仅使用 node.Attribute("Name") 也不够,因为您必须使用适当的 XName 查找该属性。 - Daniel Schaffer

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

名称是一个属性,而不是一个元素 ;) - Daniel Schaffer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接