问题
How can I pass a variable to XSLT XPath. For example
<ns0:UnitCode>
<xsl:value-of select="//ns1:Root/InputMessagePart_1/
ns2:ServiceMasterDetailsResponse/
ns2:ServiceMasterDetailResponse[$Counter]/
ns2:BASE_UOM/text()"/>
</ns0:UnitCode>
where Counter
is my XSLT variable.
I want to pass the numeric value of the variable counter to the above XSLT XPath expression.
回答1:
How to Use Variable References in XSLT
XPath
Within a select
attribute, use $var
(as you've done):
<xsl:value-of select="/path/to/element[@id=$var]"/>
Here are some other ways variable references can be used in XSLT...
Match patterns
XSLT 1.0: Variables are not allowed in match
:
It is an error for the value of the match attribute to contain a VariableReference.
XSLT 2.0: Variables are allowed in match
predicates or
Patterns may start with an id FO or key function call, provided that the value to be matched is supplied as either a literal or a reference to a variable or parameter, and the key name (in the case of the key function) is supplied as a string literal. These patterns will never match a node in a tree whose root is not a document node.
XSLT 2.0 Match Predicate Variable Example:
<xsl:variable name="globalVar" select="'value'"/>
<xsl:template match="abc[. = $globalVar]">
Literal result element
Within literal result element, use an attribute value template:
<img src="{$var}/image.jpg"/>
Element or attribute name
Within an element or attribute name, use xsl:element
or xsl:attribute
and an attribute value template:
<xsl:element name="{$var}">content</xsl:element>
or
<xsl:attribute name="{$var}">content</xsl:attribute>
来源:https://stackoverflow.com/questions/36622647/how-do-i-pass-a-variable-to-xslt-xpath-expression