Click here to Skip to main content
15,846,346 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
using Linq i wan to trap/check if element outside parent.

example:
<doc>
<x><p>text<p></x>--this is correct

<p>some text<p> --this should be inside <x> tag
<x><p>text<p></x>--this is correct
</doc>

expected:
<doc>
<x>
<p>text<p>
</x>
<x>
<p>some text<p>
<p>text<p>
</x>
</doc


What I have tried:

i tried to find it in net but no avail. thanks a lot for the help
Posted
Updated 27-Jan-17 3:44am

1 solution

Simple: find all the <p> nodes that don't have an <x> node as their immediate parent.
C#
IEnumerable<XElement> invalidNodes = document.Descendants("p").Where(p => p.Parent.Name != "x");

Or, if the <p> node can be nested at any depth under an <x> node, check the ancestors:
C#
IEnumerable<XElement> invalidNodes = document.Descendants("p").Where(p => !p.Ancestors("x").Any());
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900