Reputation: 843
I need help here to remove the xml node based on some condition
Here is my 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>
Out of this xml, based on first and last name, remove the rest of "auto" node
Keep "auto" node if First name = John and Last name = D
Expected 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>
I am tring to extract the required content first by
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;
Please suggest me here.
Upvotes: 0
Views: 1510
Reputation: 2220
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);
Print:
<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>
Link: https://dotnetfiddle.net/ZZ2Hlr
Upvotes: 2