使用LINQ删除XML文档中的重复值

时间:2013-10-26 12:14:17

标签: .net xml vb.net linq duplicates

如何删除XML文档中重复的属性值?

这是一个示例XML,其中1个重复的“名称”值为3 Ways - Fake Love

<?xml version="1.0" encoding="Windows-1252"?>
<!--MasterMusik Song Database-->
<Songs>
  <Song><Name>3 Ways - Fake Love</Name><Year>2000-2006</Year><Genre>Dance</Genre><Bitrate>128</Bitrate><Length>03:50</Length><Size>3,51</Size></Song>
  <Song><Name>3 Ways - Fake Love</Name><Year>2000-2006</Year><Genre>Dance</Genre><Bitrate>128</Bitrate><Length>03:50</Length><Size>3,51</Size></Song>
  <Song><Name>A7 - Piece Of Heaven</Name><Year>2000-2006</Year><Genre>Dance</Genre><Bitrate>128</Bitrate><Length>03:27</Length><Size>3,17</Size></Song>
 </Songs>

使用此函数,我按照“Name”值对XML元素进行排序,并尝试使用Distinct方法删除重复的名称,但这样做无效。

Private Function Sort_XML_By_Element(ByVal XML As XDocument, _
                                 ByVal Root_Element As String, _
                                 ByVal Element_to_sort As String) As XDocument

    Dim xdoc As XDocument

    xdoc = XML
    xdoc.Root.ReplaceNodes(XML.Root.Elements(Root_Element) _
                              .OrderBy(Function(sort) sort.Element(Element_to_sort).Value).Distinct)

    Return xdoc

End Function

1 个答案:

答案 0 :(得分:4)

使用Remove扩展方法代替Distinct。此方法将从文档中删除所有选定的节点。 C#代码:

xdoc.Root.Elements("Song")
    .GroupBy(s => (string)s.Element("Name"))
    .SelectMany(g => g.Skip(1)) // select all nodes from group except first one
    .Remove();

VB

xdoc.Root.<Song> _
    .GroupBy(Function(s) CStr(s.Element("Name"))) _
    .SelectMany(Function(g) g.Skip(1)) _
    .Remove()