Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何按属性对XDocument排序?_C#_Sorting_Linq To Xml - Fatal编程技术网

C# 如何按属性对XDocument排序?

C# 如何按属性对XDocument排序?,c#,sorting,linq-to-xml,C#,Sorting,Linq To Xml,我有一些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"); XDoc

我有一些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));

我这样做了,但我有一个例外。“至少有一个对象必须实现IComparable”。它必须是
node.Attribute(“Name”).Value
FYI,执行stright
node.Attribute(“Name”)。Value
会使您在缺少该属性时打开空引用异常。另外,如果XML文档指定了一个模式,那么仅仅执行
node.Attribute(“Name”)
也是不够的,因为您必须使用适当的
XName
来查找属性。Name是一个属性,而不是一个元素;)
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));