XPath 获取没有父节点的所有子节点(元素、注释和文本) [英] XPath to get all child nodes (elements, comments, and text) without parent
问题描述
我需要一个 XPath 来获取所有没有父元素的子节点(包括文本元素、注释元素和子元素).任何帮助
I need an XPath to fetch all ChildNodes ( including Text Element, Comment Element & Child Elements ) without Parent Element. Any help
示例:
<DOC>
<PRESENTEDIN>
<X>
First Text Node #1
<y> Y can Have Child Nodes #
<child> deep to it </child>
</y>
Second Text Node #2 <z/>
</X>
<EVTS>
<evt/>
<evt>
<mtg_descr> SAE 2006 World Congress & Exhibition </mtg_descr>
<sess_descr> Advanced Hybrid Vehicle Powertrains (Part 1 of 5) </sess_descr>
<loc> Detroit,MI,United States </loc>
<sess_prod_grp_cd> TSESS </sess_prod_grp_cd>
<sess_evt_name> P13 </sess_evt_name>
<sess_gen_num> 138352 </sess_gen_num>
<mtg_start_dt> 04/03/2006 </mtg_start_dt>
<mtg_end_dt> 04/06/2006 </mtg_end_dt>
<desig> CONGRESS-2006 </desig>
</evt>
</EVTS>
<EVTTYPE>PAPER</EVTTYPE>
<SUPERTECH>
<![CDATA[C8585]]>
</SUPERTECH>
</PRESENTEDIN>
XPATH 尝试
1. $doc/PRESENTEDIN/X
2. $doc/PRESENTEDIN/X/descendant::*
2. $doc/PRESENTEDIN/X/self::*
预期输出
First Text Node #1
<y> Y can Have Child Nodes #
<child> deep to it </child>
</y>
Second Text Node #2 <z/>
我不想
<X>
First Text Node #1
<y> Y can Have Child Nodes #
<child> deep to it </child>
</y>
Second Text Node #2 <z/>
</X>
推荐答案
来自 XPath 的文档 ( http://www.w3.org/TR/xpath/#location-paths ):
From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):
child::*
选择所有元素上下文节点的子节点
child::*
selects all element children of the context node
child::text()
选择所有文本节点上下文节点的子节点
child::text()
selects all text node
children of the context node
child::node()
选择所有上下文节点的子节点,无论他们的节点类型
child::node()
selects all the
children of the context node, whatever
their node type
所以我猜你的答案是:
$doc/PRESENTEDIN/X/child::node()
如果你想要一个所有嵌套节点的扁平数组:
And if you want a flatten array of all nested nodes:
$doc/PRESENTEDIN/X/descendant::node()
这篇关于XPath 获取没有父节点的所有子节点(元素、注释和文本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!