根据子条件删除父节点 [英] Remove the Parent Node based on Child condition
本文介绍了根据子条件删除父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助,以便根据某些条件删除xml节点
I need help here to remove the xml node based on some condition
这是我的xml
<result>
<product>
<auto>
<report>
<auto>
<admin></admin>
<report>
<search>
<subjects>
<subject>
<name>
<first>John</first>
<last>D</last>
</name>
</subject>
</subjects>
</search>
</report>
</auto>
</report>
</auto>
<auto>
<report>
<auto>
<admin></admin>
<report>
<search>
<subjects>
<subject>
<name>
<first>Jack</first>
<last>L</last>
</name>
</subject>
</subjects>
</search>
</report>
</auto>
</report>
</auto>
</product>
</result>
在此xml中,根据名字和姓氏,删除其余的自动"节点
Out of this xml, based on first and last name, remove the rest of "auto" node
如果名字= John,姓氏= D,请保留自动"节点
Keep "auto" node if First name = John and Last name = D
预期的xml:
<result>
<product>
<auto>
<report>
<auto>
<admin></admin>
<report>
<search>
<subjects>
<subject>
<name>
<first>John</first>
<last>D</last>
</name>
</subject>
</subjects>
</search>
</report>
</auto>
</report>
</auto>
</product>
</result>
我想先提取所需的内容
var query =
from p in XDocument.Parse(myXml).Root.Elements ("result/product/auto/report/auto/report/search/subjects/subject/name")
where (
from c in p.Elements("first")
where c.Value == "John"
select c
).Any()
select p;
请在这里建议我.
推荐答案
如果我对您的理解正确:
If I understand you correctly:
string first = "John";
string last = "D";
XDocument xd = XDocument.Parse(xml);
xd.Root.Element("product").Elements("auto").ToList()
.ForEach(x=>
{
var name = x.Descendants("name").First();
if (name.Element("first").Value != first
&& name.Element("last").Value != last)
x.Remove();
});
Console.WriteLine(xd);
打印:
<result>
<product>
<auto>
<report>
<auto>
<admin></admin>
<report>
<search>
<subjects>
<subject>
<name>
<first>John</first>
<last>D</last>
</name>
</subject>
</subjects>
</search>
</report>
</auto>
</report>
</auto>
</product>
</result>
链接: https://dotnetfiddle.net/ZZ2Hlr
这篇关于根据子条件删除父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文