排序XML文档

时间:2013-10-24 13:44:06

标签: .net xml vb.net linq

我有这样的XML:

<?xml version="1.0" encoding="Windows-1252"?>
<!--XML Songs Database.-->
<Songs>
    <Song><Name>My Song 2.mp3</Name><Year>2007</Year><Genre>Dance</Genre><Bitrate>320</Bitrate><Length>04:55</Length><Size>4,80</Size></Song>
    <Song><Name>My Song 1.mp3</Name><Year>2009</Year><Genre>Electro</Genre><Bitrate>192</Bitrate><Length>06:44</Length><Size>8,43</Size></Song>
    <Song><Name>My Song 3.mp3</Name><Year>2008</Year><Genre>UK Hardcore</Genre><Bitrate>128</Bitrate><Length>05:12</Length><Size>4,20</Size></Song>
</Songs>

如何通过“Name”属性重新排序列表元素以获取这样的xml文档:

<?xml version="1.0" encoding="Windows-1252"?>
<!--XML Songs Database.-->
<Songs>
    <Song><Name>My Song 1.mp3</Name><Year>2009</Year><Genre>Electro</Genre><Bitrate>192</Bitrate><Length>06:44</Length><Size>8,43</Size></Song>
    <Song><Name>My Song 2.mp3</Name><Year>2007</Year><Genre>Dance</Genre><Bitrate>320</Bitrate><Length>04:55</Length><Size>4,80</Size></Song>
    <Song><Name>My Song 3.mp3</Name><Year>2008</Year><Genre>UK Hardcore</Genre><Bitrate>128</Bitrate><Length>05:12</Length><Size>4,20</Size></Song>
</Songs> 

这就是我正在尝试的......:

Dim xml As XDocument = XDocument.Load(xmlfile)
Dim Elements As IEnumerable(Of XElement) = xml.Descendants()

xml = Elements.OrderBy(Function(name) name...)

1 个答案:

答案 0 :(得分:3)

蛮横但简单的方法:

xml.Root.ReplaceNodes(xml.Root.Elements("Song") _
                              .OrderBy(Function (s) s.Element("Name").Value))