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

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
Saravanan
  • 11,372
  • 43
  • 143
  • 213

2 Answers2

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()
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
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>
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • 5
    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. – Michael Kay Sep 07 '11 at 07:29
  • Nice xpath for identify root element, +1 – Rudramuni TP Feb 04 '15 at 19:06