我有一个这样的xml文件:
<Root>
<Combination Id="A35">
<Level Id="1">
<Option Id="S10" Time="07:30" Date="02-10-2013"/>
<Option Id="S13" Time="08:30" Date="03-10-2013"/>
<Option Id="S15" Time="08:30" Date="01-10-2013"/>
</Level1>
<Level Id="2">
<Option Id="S25" Time="07:30" Date="02-10-2013"/>
<Option Id="S26" Time="08:30" Date="03-10-2013"/>
</Level1>
</Combination>
<Combination Id="A23">
<Level Id="1">
<Option Id="S13" Time="09:30" Date="02-10-2013"/>
<Option Id="S8" Time="07:30" Date="01-10-2013"/>
</Level>
<Level Id="2">
<Option Id="S10" Time="07:30" Date="02-10-2013"/>
<Option Id="S13" Time="08:30" Date="03-10-2013"/>
</Level>
</Combination>
.....
</Root>我想按节点选项中的日期和时间属性对其进行排序(每个选项都有自己的排序),但也要按带有id=1的Level node中的一些选项节点中的最早值排序(因此组合节点的顺序会发生变化):
<Root>
<Combination Id="A23">
<Level Id="1">
<Option Id="S8" Time="07:30" Date="01-10-2013"/>
<Option Id="S13" Time="09:30" Date="02-10-2013"/>
</Level1>
<Level Id="2">
<Option Id="S10" Time="07:30" Date="02-10-2013"/>
<Option Id="S13" Time="08:30" Date="03-10-2013"/>
</Level1>
</Combination>
<Combination Id="A35">
<Level Id="1">
<Option Id="S15" Time="08:30" Date="01-10-2013"/>
<Option Id="S10" Time="07:30" Date="02-10-2013"/>
<Option Id="S13" Time="08:30" Date="03-10-2013"/>
</Level1>
<Level Id="2">
<Option Id="S25" Time="07:30" Date="02-10-2013"/>
<Option Id="S26" Time="08:30" Date="03-10-2013"/>
</Level1>
</Combination>
.....
</Root>有没有可能用LINQ2XML来实现呢?或者为了获得我想要的顺序,日期和时间属性应该存在于组合节点中?
发布于 2013-10-08 23:01:01
是的,可以使用LINQ to XML来完成,但是,查询相当可怕:
// load XML into XDocument instance
var xDoc = XDocument.Load("Input.txt");
// create new XDocument using info from the loaded one
var xDoc2 = new XDocument(
new XElement("Root",
xDoc.Root
.Elements("Combination")
.Select(c => new XElement("Combination",
c.Attributes(),
c.Elements("Level")
.Select(l => new XElement("Level",
l.Attributes(),
l.Elements("Option")
.OrderBy(o => (DateTime)o.Attribute("Date") + TimeSpan.Parse((string)o.Attribute("Time")))))))
.OrderBy(c => c.Elements("Level")
.First(l => (int)l.Attribute("Id") == 1)
.Elements("Option")
.Select(o => (DateTime)o.Attribute("Date") + TimeSpan.Parse((string)o.Attribute("Time")))
.First())
));
// save the new document
xDoc2.Save("Input.txt");https://stackoverflow.com/questions/19243358
复制相似问题