因此,我有一个XML元素列表,希望通过这些列表并删除重复的元素。随着循环的进行,如果在当前索引和索引+1之间找到重复项,则需要删除索引+1,并且应该与索引进行比较的下一个值应该是索引+2,依此类推,直到序列中没有重复项为止。如果index + 3与index相比不是重复项,则该循环应按常规侦查顺序重复进行。
<Update>
<Properties id="42" rotation="0.00 0.00 -0.01" />
</Update>
<Update>
<Properties id="42" rotation="0.00 0.00 -0.01" />
</Update>
<Update>
<Properties id="42" rotation="0.00 0.00 -0.01" />
</Update>
<Update>
<Properties id="42" rotation="2.42 2.24 -4.42" />
</Update>
我目前正在使用LinQ来操纵XDocument元素。目前,我正在使用If语句将索引与index + 1进行比较,如果它们相同,则删除index + 1。当我++;然后索引现在位于先前已删除属性的位置,因此,如果下一个索引+1现在包含与索引-2相同的值(因为我们在下一次迭代时将其增加1),则不会记录顺序重复项。当前输出:
if (xmlElementList.Count() > 1) {
// Start looping through all modifications
for (int i = 0; i < xmlElementList.Count() - 1; i++) {
var currEl = xmlElementList.ElementAt(i).Element("Properties");
var nextEl = xmlElementList.ElementAt(i+1).Element("Properties");
// Check for duplicate rotation attributes
if (currEl.Attribute("rotation") != null) {
if (currEl.Attribute("rotation ").Value ==
nextEl.Attribute("rotation ").Value) {
nextEl.Attribute("rotation ").Remove();
}
}
}
}
<Update>
<Properties id="42" rotation="0.00 0.00 -0.01" />
</Update>
<Update>
<Properties id="42" />
</Update>
<Update>
<Properties id="42" rotation="0.00 0.00 -0.01" />
</Update>
<Update>
<Properties id="42" rotation="2.42 2.24 -4.42" />
</Update>
一个序列中不应有两个重复项。如果文件本身中存在重复项,那很好,但index + 1不应包含与index相同的值。预期输出:
<Update>
<Properties id="42" rotation="0.00 0.00 -0.01" />
</Update>
<Update>
<Properties id="42" />
</Update>
<Update>
<Properties id="42" />
</Update>
<Update>
<Properties id="42" rotation="2.42 2.24 -4.42" />
</Update>
当前方法的问题是,您正在提前考虑哪个元素。在首次出现匹配项时,您应该将原始的第一项与第二项进行比较。您只在查看相邻的项目。
您可以设计一个xpath查询,可以很容易地选择ID和旋转度与前一个相同的<Update>
个元素。
//Update[preceding-sibling::Update/Properties/@id =Properties/@id
and preceding-sibling::Update/Properties/@rotation=Properties/@rotation]
然后根据需要更改这些元素。
var xpath = "//Update[preceding-sibling::Update/Properties/@id=Properties/@id and preceding-sibling::Update/Properties/@rotation=Properties/@rotation]";
var fixUpdates = doc.XPathSelectElements(xpath);
var fixProperties = fixUpdates.Elements("Properties");
var removeMe = fixProperties.Attributes("rotation");
removeMe.Remove();