我有这样的XML格式:
<?xml version="1.0" encoding="Windows-1252"?>
<!--MasterMusik Video Database-->
<Videos>
<Video><Name>SKRILLEX & WOLFGANG GARTNER - THE DEVIL's DEN</Name><Genre>Techno</Genre><Format>mp4</Format><HD>HD</HD><Resolution>1280x720</Resolution><Size>70,57</Size></Video>
<Video><Name>4 Strings - Let It Rain</Name><Genre>Dance</Genre><Format>mp4</Format><HD>HD</HD><Resolution>1920x1080</Resolution><Size>129,3</Size></Video>
<Video><Name>Deadmau5 - I Remember (Live At Roskilde Festival)</Name><Genre>Trance</Genre><Format>mkv</Format><HD>SD</HD><Resolution>704x384</Resolution><Size>97,99</Size></Video>
</Videos>我想根据元素的“名称”标签对它们进行排序。
这是我用来对元素Sort XML document排序的函数
Private Function XML_Sort(ByVal xdoc As XDocument, _
ByVal Root_Element As String, _
ByVal Element_to_sort As String) As XDocument
Try
xdoc.Root.ReplaceNodes(xdoc.Root.Elements(Root_Element) _
.OrderBy(Function(sort) sort.Element(Element_to_sort).Value))
Return xdoc
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function但是我得到的输出是完全缩进的:
<!--MasterMusik Video Database-->
<Videos>
<Video>
<Name>4 Strings - Let It Rain</Name>
<Genre>Dance</Genre>
<Format>mp4</Format>
<HD>HD</HD>
<Resolution>1920x1080</Resolution>
<Size>129,3</Size>
</Video>
<Video>
<Name>Deadmau5 - I Remember (Live At Roskilde Festival)</Name>
<Genre>Trance</Genre>
<Format>mkv</Format>
<HD>SD</HD>
<Resolution>704x384</Resolution>
<Size>97,99</Size>
</Video>
<Video>
<Name>SKRILLEX & WOLFGANG GARTNER - THE DEVIL's DEN</Name>
<Genre>Techno</Genre>
<Format>mp4</Format>
<HD>HD</HD>
<Resolution>1280x720</Resolution>
<Size>70,57</Size>
</Video>
</Videos>这是我正在使用的用法:
Dim xdoc As XDocument = _
XDocument.Load("Videos.xml", LoadOptions.PreserveWhitespace)
xdoc = XML_Sort(xdoc, "Video", "Name")
IO.File.WriteAllText("Sorted Videox.xml", xdoc.ToString)在这一点上有两个问题:
<?xml version="1.0" encoding="Windows-1252"?>,我需要手动编写它。我怎样才能解决这两个问题?
发布于 2013-10-29 15:23:21
一旦开始操作XDocument,格式就会丢失。排序方法只返回一个纯XML元素的列表。因此,您有两个选择:
<Name>是行中的第一个标记,所以只按字母顺序排序文本行就足够了:
Dim line = File.ReadAllLines("Videos.xml") Dim toSort = lines.Skip(3).Take(lines.Length - 4)‘跳过前三行和最后一行’Dim结果=Videos.xml s).Concat({lines.Last}) File.WriteAllLines("Sorted.xml",result.ToArray())发布于 2013-10-27 09:47:32
尝尝这个
IO.File.WriteAllText("Sorted Videox.xml", xdoc.ToString(SaveOptions.DisableFormatting))https://stackoverflow.com/questions/19616639
复制相似问题