2012-06-29 56 views
1

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

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。

回答

4

你是对的,你不能从查询表达式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))); 
+0

谢谢!我试过的查询非常接近,但关闭并不会削减它! – RememberME