Using XSL to pass an XML attribute as an id into H

2019-08-07 20:00发布

问题:

Hope you can help point me in the right direction with this problem...

What I am trying to do: I have an XML file that I'm turning into HTML using XSLT. Part of that includes adding a "hide" button. I want to use the hide button to remove the node from the XML, and my idea is to give the button the same id as the myId attribute in the relevant XML element, which makes it easy to match the onClick of the button with the XML element to hide.

Here's a bit of the XML:

<sectionStatement myId="1">Awesome statement</sectionStatement>
<sectionStatement myId="2">I am a statement</sectionStatement>
<sectionStatement myId="3">I am another statement</sectionStatement>

Here's a bit of the XSL where I' stuck:

<xsl:for-each select="sectionStatement">
  <p><xsl:value-of select="."/><a class='showHideBtn' href='#'>Hide</a></p>
</xsl:for-each>

...so I want to end up with 3 paras of html, each with a "Hide" button, and I want the button to have the relevant id (1,2 or 3). It is the equivalent of adding id="<xsl:value-of select='@myId'/>" into the tag ...but I've tried that and it doesn't work!

Thanks for your advice :-) Mark

回答1:

Use an attribute value template <a id="{@myId}" class="showHideBtn" href="#">Hide</a>.



回答2:

You could use xsl:attribute to add dynamic, conditional attributes and apply templates to elements.

<p>
   <xsl:attribute name="id">
    optionalText<xsl:value-of select="@myId"/>
   </xsl:attribute>
</p>

If you already know the value, the transformation syntax is simpler.

<xsl:for-each select="sectionStatement">
  <p><xsl:value-of select="."/>
    <a class='showHideBtn' href='#' id='{@myId}'>
    Hide
    </a>
  </p>
</xsl:for-each>