首先,我感谢大家对我的问题的耐心。我在这里搜索了 为什么这段代码在 xml 元素中找不到任何重复项? 并 使用 linq 从 xml 中删除重复的元素(具有特定值) 并且很接近,但没有得到它。
我需要删除 XML 中的重复元素。这些元素可能存在也可能不存在
XML 片段如下所示。需要删除重复的 BuildNumber 元素。
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ProductSessions FileID="{C7DCB747-AB3A-4222-B14B-F7A7994C212F}">
<Session LicenceNumber="E2240A66AC64CB770000" SessionGuid="{20c5d49e-7442-4fd0-b612-23aa743f4bd9}" FK_FileId="{C7DCB747-AB3A-4222-B14B-F7A7994C212F}">
<TimeOpened>2013/10/14 11:18:43</TimeOpened>
<LicenseInfo Configuration="XYZ" Description="Company Standard Config+More" DongleID="-error-no-dongle-" LicenseKey="FLEXlm Server Licence" Licensed="Company USA" FK_Sess ionGuid="{20c5d49e-7442-4fd0-b612-23aa743f4bd9}" />
<ProductVersion>Product 9.0.0 NTx86-64 (build 987)</ProductVersion>
<BuildNumber>987</BuildNumber>
<ProductArchitecture>NTx86-64</ProductArchitecture>
<ProductVersion>9.0.0</ProductVersion>
<SystemInfo OperativeSystem="Microsoft Windows 8 Enterprise Edition (build 9200) 64-bit" User=" " FK_SessionGuid="{20c5d49e-7442-4fd0-b612-23aa743f4bd9}" />
<ApplicationName>X</ApplicationName>
<TimeClosed>2013/10/14 11:42:57</TimeClosed>
</Session>
<Session LicenceNumber="E2240A66AC64CB770000" SessionGuid="{5682f705-baa1-46c0-a5ca- 3c6d816c94cc}" FK_FileId="{C7DCB747-AB3A-4222-B14B-F7A7994C212F}">
<TimeOpened>2013/10/14 11:55:23</TimeOpened>
<LicenseInfo Configuration="XYZ" Description="Company Standard Config+More" DongleID="-error-no-dongle-" LicenseKey="FLEXlm Server Licence" Licensed="Company USA" FK_SessionGuid="{5682f705-baa1-46c0-a5ca-3c6d816c94cc}" />
<ProductVersion>Product 8.2.x NTx86-64 (build 123)</ProductVersion>
<BuildNumber>123</BuildNumber>
<BuildNumber>123</BuildNumber>
<BuildNumber>123</BuildNumber>
<ProductArchitecture>NTx86-64</ProductArchitecture>
<ProductVersion>8.2.x</ProductVersion>
<SystemInfo OperativeSystem="Microsoft Enterprise Edition (build 9200) 64-bit" User=" " FK_SessionGuid="{5682f705-baa1-46c0-a5ca-3c6d816c94cc}" />
<ApplicationName>X</ApplicationName>
<TimeClosed>2013/10/14 11:58:20</TimeClosed>
</Session>
}
我的代码如下
// This gets the correct # of sessions
IEnumerable<XElement> childElements =
from element in XmlFile.Elements().Descendants("Session")
select element;
foreach (XElement el in childElements)
{
var dups = XmlFile.Descendants(el.n).GroupBy(e => e.Descendants("BuildNumber").First().ToString());
//remove the duplicates
foreach (XElement ele in dups.SelectMany(g => g.Skip(1)))
ele.Remove();
谁能指出我正确的方向?