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

标签 c# xml linq icomparer

我需要对 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)));

关于c# - 使用 IComparer 对 xml 中的节点进行排序/排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11269472/

相关文章:

c# - 具有不同签名的函数,但编译器调用了错误的函数

c# - 创建一个 NUnit 约束,意思是 "{collection} does not contain {item}"

c# - EntityFramework 核心单元测试 - SQLite 内存模式与 InMemory 提供程序

android - 如何更改标题栏的颜色

c# - 如何在多个实体数据模型之间共享连接字符串

c# - 如何从 'Guid' 返回 'Nullable<Guid>' ?

具有递归关系的聚合计数的 LINQ 查询

c# - 相同的 DbContext 在解决方案的不同项目下表现不同

php - 如何在PHP中检查它是一个xml文件还是一个json文件

java - 如何将 XML(字符串)附加到已创建文档开头的 XmlEventWriter (StAX)