In XSLT, why can't I set the select attribute from a value using the xsl attribute: what's a good alternative?

I have a constant and a variable that I wann mouch together to select a specific node, this is what I want to do:

<xsl:attribute name="value">
 <xsl:value-of>
  <xsl:attribute name="select">
   <xsl:text>/root/meta/url_params/
   <xsl:value-of select="$inputid" />
  </xsl:attribute>
 </xsl:value-of>
</xsl:attribute>

Why does this not work, and what can I do instad?

+3
source share
2 answers

While @Alejandro is right that in the general case a dynamic assessment will be required (and this may be provided for in XSLT 2.1+), simpler cases are possible.

For example, if it $inputidcontains only a name, you probably want this :

<xsl:value-of select="/root/meta/url_params/*[name()=$inputid]"/>

XPath, :

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:param name="inputId" select="'param/yyy/value'"/>

 <xsl:variable name="vXpathExpression"
  select="concat('root/meta/url_params/', $inputId)"/>

 <xsl:template match="/">
  <xsl:value-of select="$vXpathExpression"/>: <xsl:text/>

  <xsl:call-template name="getNodeValue">
    <xsl:with-param name="pExpression"
         select="$vXpathExpression"/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="getNodeValue">
   <xsl:param name="pExpression"/>
   <xsl:param name="pCurrentNode" select="."/>

   <xsl:choose>
    <xsl:when test="not(contains($pExpression, '/'))">
      <xsl:value-of select="$pCurrentNode/*[name()=$pExpression]"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:call-template name="getNodeValue">
        <xsl:with-param name="pExpression"
          select="substring-after($pExpression, '/')"/>
        <xsl:with-param name="pCurrentNode" select=
        "$pCurrentNode/*[name()=substring-before($pExpression, '/')]"/>
      </xsl:call-template>
    </xsl:otherwise>
   </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

, XML-:

<root>
  <meta>
    <url_params>
      <param>
        <xxx>
          <value>5</value>
        </xxx>
      </param>
      <param>
        <yyy>
          <value>8</value>
        </yyy>
      </param>
    </url_params>
  </meta>
</root>

, :

root/meta/url_params/param/yyy/value: 8
+6

XPath XSLT 1.0

, , $inputid, .

/root/meta/url_params/$inputid , / XPath 1.0 ( XPath 2.0 ).

:

/root/meta/url_params/*[name()=$inputid]

/root/meta/url_params/*[@id=$inputid]

Walker, , .

+5

Source: https://habr.com/ru/post/1760733/


All Articles