父元素之外的Xdocument陷阱元素 [英] Xdocument trap element outside parent elemet
本文介绍了父元素之外的Xdocument陷阱元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Linq我想捕获/检查父元素之外的元素。
例如:
< doc>
< x>< p> text< p>< / x> - 这是正确的
< p>一些文字< p> - 这应该在< x>里面了tag
< x>< p> text< p>< / x> - 这是正确的
< / doc>
预期:
< doc>
< x>
< p> text< p>
< / x>
< x>
< p>一些文字< p>
< p> text< p>
< / x>
< / doc
我尝试过:
我试图在网上找到它但无济于事。非常感谢你的帮助
解决方案
简单:找到所有< p>
没有< x>
节点作为其直接父节点的节点。
IEnumerable<的XElement> invalidNodes = document.Descendants( p)。其中(p = > p.Parent.Name!= x);
或者,如果< p>
节点可以嵌套在下的任何深度< x>
节点,检查祖先:
IEnumerable< XElement> invalidNodes = document.Descendants( p)。其中(p = > !p.Ancestors( x)。Any() );
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
解决方案
Simple: find all the<p>
nodes that don't have an<x>
node as their immediate parent.
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:
IEnumerable<XElement> invalidNodes = document.Descendants("p").Where(p => !p.Ancestors("x").Any());
这篇关于父元素之外的Xdocument陷阱元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文