我有一个字符串,如下所示
<RuleGeneratorContextMenuXML>
<Contains>Principal Amount</Contains>
<NotContains />
<Contains>Principal Amount</Contains>
<NotContains />
<Contains>Interest Payment Date</Contains>
<NotContains />
<Contains />
<NotContains>Interest Payment Date</NotContains>
<Contains />
<NotContains>Interest Payment Date</NotContains>
<Contains />
<NotContains>Maturity falls</NotContains>
</RuleGeneratorContextMenuXML>
我使用xDocument像
一样解析它string keywords =“
<RuleGeneratorContextMenuXML>
<Contains>Principal Amount</Contains>
<NotContains />
<Contains>Principal Amount</Contains>
<NotContains />
<Contains>Interest Payment Date</Contains>
<NotContains />
<Contains />
<NotContains>Interest Payment Date</NotContains>
<Contains />
<NotContains>Interest Payment Date</NotContains>
<Contains />
<NotContains>Maturity falls</NotContains>
</RuleGeneratorContextMenuXML>
“
var x Doc = xDocument.Parse.Parse(Keywords);
从x Doc我想根据值删除重复的元素。所以我的结果x Doc应该是
<RuleGeneratorContextMenuXML>
<Keywords>
<Contains>Principal Amount</Contains>
<Contains>Interest Payment Date</Contains>
<NotContains>Interest Payment Date</NotContains>
<NotContains>Maturity falls</NotContains>
</Keywords>
</RuleGeneratorContextMenuXML>
这是我到目前为止所尝试的
for each (var node in xDoc. Descendants().Where(x => "Contains NotContains" .Contains(x.Name.Local Name)))
{
if (node.Value == "")
{
node.Remove();
}
}
但这并没有达到我想要的目的。非常感谢任何帮助。
答案 0 :(得分:0)
评论中的代码已结束。您需要按值对特定名称的元素进行分组,然后在它们为空的情况下删除所有元素,或者在它们具有值的情况下删除除第一个之外的所有元素:
Kill
您可以以相同的方式实施doc.Descendants("Contains")
.GroupBy(x => x.Value)
.SelectMany(x => x.Key == string.Empty ? x : x.Skip(1))
.Remove();
,或理想地重构以删除重复。
请参阅this fiddle了解演示。