Chaegie Ответов: 1

XDocument trap элемент вне родительского элемента


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


Что я уже пробовал:

i tried to find it in net but no avail. thanks a lot for the help

1 Ответов

Рейтинг:
1

Richard Deeming

Просто: найти все <p> узлы, которые не имеют <x> узел как их непосредственный родитель.

IEnumerable<XElement> invalidNodes = document.Descendants("p").Where(p => p.Parent.Name != "x");

Или, если <p> узел может быть вложен на любой глубине под <x> узел, проверь предков:
IEnumerable<XElement> invalidNodes = document.Descendants("p").Where(p => !p.Ancestors("x").Any());