Skip to main content
 首页 » 编程设计

c#之使用 IComparer 对 xml 中的节点进行排序/排序

2024年02月20日9bhlsheji

我需要对 xml 中的节点进行排序。我有以下代码可以成功地按字母顺序排列它们。但是,尽管允许使用字符串,但大部分数据都是数字。我有一个 IComparer 设置,可以正确排序数据,因为我希望它出现在其他地方。

System.Xml.Linq.XDocument output = new System.Xml.Linq.XDocument( 
                    new System.Xml.Linq.XElement("xml", 
                from node in input.Root.Elements("training") 
                orderby node.Attribute("order").Value 
                select node)); 

我已经找到如何在方法调用中使用 IComparer,.OrderBy(x => x, new CustomComparer()) 但是,我还没有弄清楚如何将其用于使用 xml。根据我在网上阅读的内容,我似乎无法从查询语法中调用 IComparer。

请您参考如下方法:

你是对的,你不能使用查询表达式 orderby 子句中的重载。幸运的是,您的查询非常简单,因此您可以使用:

// Have a using directive for System.Xml.Linq - it'll make everything simpler! 
XDocument output = new XDocument( 
    new XElement("xml", 
        input.Root 
             .Elements("training") 
             .OrderBy(node => node.Attribute("order)".Value, comparer)));