使用 Linq to XML(有点笨拙):
//elem is an XElement containing the XML
var duplicateRanges = (
from head in elem.Elements()
let currentClass = (string)head.Attribute("class")
let others = head.ElementsAfterSelf().TakeWhile(next => {
if (next.NodesBeforeSelf().LastOrDefault().NodeType == XmlNodeType.Text) { return false; }
return (string)next.Attribute("class") == currentClass;
})
where others.Any()
select new {
head,
others
}).ToList();
foreach (var range in duplicateRanges) {
range.head.Value=(string)range.head + String.Join("", from o in range.others select (string)o);
foreach (var other in range.others) {
other.Remove();
}
}
这可能足以满足您的目的,但它有一个主要限制:它将破坏要删除的跨度中的任何子节点。只有文本将被保留并与第一个跨度合并。