Home > Enterprise >  Access the n-th child of root element in XSLT
Access the n-th child of root element in XSLT

Time:12-21

I'm parsing this XSLT file

merge_file = merge_xslt(initial_message, depth=et.XSLT.strparam("5"))

where initial_message = et.parse(initial.xslt')

What i want to achieve is to pass to the initial.xslt the depth param. The initial.xslt code is here:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" omit-xml-declaration="no" indent="yes" encoding="utf-8"/>
    <xsl:template match="xsl:template[not(@name)]">
     <xsl:param name="depth" />
     <xsl:copy>
        <xsl:apply-templates select="*|@*"/>
        <!-- The path /*/*[depth]/* is used to select the third child element of the root
        element of the document, and then all of its child elements. -->
        <xsl:copy-of select="document('second.xslt')/*/*[$depth]/*"/>
     </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

But this approach is not working and im wondering what im missing. The depth variable is not passing

CodePudding user response:

If you run XSLT 1.0 with Python lxml I would suggest to use version="1.0" for better error reporting.

As for the code, if you want to be able to set the global parameter depth from outside then it needs to be declared outside of any xsl:template, as a child of xsl:stylesheet e.g.

<xsl:param name="depth" />

<xsl:template match="xsl:template[not(@name)]">
     <xsl:copy>
        <xsl:apply-templates select="*|@*"/>
        <!-- The path /*/*[depth]/* is used to select the third child element of the root
        element of the document, and then all of its child elements. -->
        <xsl:copy-of select="document('second.xslt')/*/*[$depth]/*"/>
     </xsl:copy>
</xsl:template>

Make sure you pass in a number value or better use [position() = $depth] or [number($depth)] if you can't assure from Python you pass in a number.

  • Related