XPath to get all child nodes (elements, comments, and text) without parent

后端 未结 2 607
不知归路
不知归路 2020-12-04 19:09

I need an XPath to fetch all ChildNodes ( including Text Element, Comment Element & Child Elements ) without Parent Element. Any help

Sample Example:

<         


        
相关标签:
2条回答
  • 2020-12-04 19:41

    From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):

    child::* selects all element children of the context node

    child::text() selects all text node children of the context node

    child::node() selects all the children of the context node, whatever their node type

    So I guess your answer is:

    $doc/PRESENTEDIN/X/child::node()
    

    And if you want a flatten array of all nested nodes:

    $doc/PRESENTEDIN/X/descendant::node()
    
    0 讨论(0)
  • 2020-12-04 19:45

    Use this XPath expression:

    /*/*/X/node()
    

    This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

    To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes"/>
     <xsl:template match="/">
      <xsl:copy-of select="/*/*/X/node()"/>
     </xsl:template>
    </xsl:stylesheet>
    

    and it produces exactly the wanted, correct result:

       First Text Node #1            
        <y> Y can Have Child Nodes #                
            <child> deep to it </child>
        </y>            Second Text Node #2 
        <z />
    

    Explanation:

    1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

    2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

    0 讨论(0)
提交回复
热议问题