Reputation: 561
I would like to select nodes using the XPath which is defined in an attribute in the same XML document. An example XML file:
<section count-node="table/row">
<table>
<row>row1</row>
<row>row2</row>
<row>row3</row>
</table>
</section>
Now I would like to use XSLT to get the number of rows, e.g.
<xsl:template match="section">
<xsl:variable name="count" select="count({MY VALUE FOR @count-node}})"/>
<xsl:value-of select="$count"/>
</xsl:template>
where
count({MY VALUE FOR @count-node}})
should be replaced by
count(/table/row)
when processing the stylesheet. This should of course return
3
I cannot use '/table/row' in the stylesheet as I do not know the content of the element. It does not have to be a table, or the table maybe nested.
How can I do this?
Upvotes: 1
Views: 260
Reputation: 66714
If your XPath expressions are rather simple, then the following might work:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="section">
<xsl:variable name="expression" select="@count-node" as="node()"/>
<xsl:value-of select="count(
descendant::*[$expression =
string-join(
(ancestor::*[.=$expression/../descendant::*]/name(),
name()),
'/')] )"/>
</xsl:template>
</xsl:stylesheet>
It counts all of the descendant elements who's computed XPath (relative from the section
) is equal to the XPath from the @count-node
.
Upvotes: 2