Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting section of XSLT to single node

Tags:

xslt

Is there a way of restricting a section of XSLT to a single node, so that the entire path of the node is not necessary each time?

For example...

Name: <xsl:value-of select="/root/item[@attrib=1]/name"/>
Age: <xsl:value-of select="/root/item[@attrib=1]/age"/>

This could be done via a for-each command, but I am led to believe that these should be avoided if at all possible...

<xsl:for-each select="/root/item[@attrib=1]"/>
  Name: <xsl:value-of select="name"/>
  Age: <xsl:value-of select="age"/>
</xsl:for-each>

I guess I'm asking if there is an XSLT equivalent of the VB.NET With command?

I would prefer to avoid xsl:template for readability, as the XSLT file in question is large, but happy to accept if that is the only way to do it. And if so, what is the syntax to call a particular template based on specific node?

Update

In follow up to the answer by @javram, it is possible to match separate templates based on particular attributes / nodes.

<xsl:apply-templates select="/root/item[@attrib=1]"/>
<xsl:apply-templates select="/root/item[@attrib=2]"/>

<xsl:template match="/root/item[@attrib=1]">
  Name: <xsl:value-of select="name"/>
  Age: <xsl:value-of select="age"/>
</xsl:template>

<xsl:template match="/root/item[@attrib=2]">
  Foo: <xsl:value-of select="foo"/>
</xsl:template>
like image 380
freefaller Avatar asked Oct 09 '22 06:10

freefaller


2 Answers

The correct way would be to use a template:

<xsl:apply-templates select="/root/item[@attrib=1]"/>

.
.
.

<xsl:template match="/root/item">
     Name: <xsl:value-of select="name"/>
     Age: <xsl:value-of select="age"/>
</xsl:template>
like image 91
javram Avatar answered Oct 12 '22 12:10

javram


You may use variables:

<xsl:variable name="foo" select="/root/item[@attrib=1]" />

<xsl:value-of select="$foo/name" />
<xsl:value-of select="$foo/age" />
like image 24
mortb Avatar answered Oct 12 '22 11:10

mortb