how to check parent of current node is root node or not in xslt?
Asked Answered
C

2

10

I want to check the parent of current node is root node or not in Xslt.How i do that? Please Guide me to get out of this issue...

Thanks & Regards, P.SARAVANAN

Complexioned answered 7/9, 2011 at 5:40 Comment(1)
Good question, +1. See my answer for correct solutions, both in XPath 1.0 and in XPath 2.0.Elite
E
8

You can use not(ancestor::*).

Usage Example:

  <xsl:template match="node()|@*">
    <xsl:if test="not(ancestor::*)">
      <xsl:message>The root element is "<xsl:value-of select="name()"/>".</xsl:message>
    </xsl:if>
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
Equable answered 7/9, 2011 at 5:52 Comment(2)
Two qualifications: (a) this is OK for XSLT 1.0, where the root node is always the document node; it's not OK for 2.0, where the root node might be an element node (or indeed an attribute or text node). (b) The code given is OK except for the message. A comment or processing instruction that is a child of the root (document) node will satisfy the test, but produce a spurious message.Cabbagehead
Nice xpath for identify root element, +1Ungley
E
9

In XPath 1.0 (XSLT 1.0):

not(parent::*)

Or you may use:

generate-id(..) = generate-id(/)

In XPath 2.0 (XSLT 2.0):

.. is root()
Elite answered 7/9, 2011 at 13:25 Comment(0)
E
8

You can use not(ancestor::*).

Usage Example:

  <xsl:template match="node()|@*">
    <xsl:if test="not(ancestor::*)">
      <xsl:message>The root element is "<xsl:value-of select="name()"/>".</xsl:message>
    </xsl:if>
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
Equable answered 7/9, 2011 at 5:52 Comment(2)
Two qualifications: (a) this is OK for XSLT 1.0, where the root node is always the document node; it's not OK for 2.0, where the root node might be an element node (or indeed an attribute or text node). (b) The code given is OK except for the message. A comment or processing instruction that is a child of the root (document) node will satisfy the test, but produce a spurious message.Cabbagehead
Nice xpath for identify root element, +1Ungley

© 2022 - 2024 — McMap. All rights reserved.