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

2019-08-07 19:39发布

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

2条回答
走好不送
2楼-- · 2019-08-07 19:59

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>
查看更多
3楼-- · 2019-08-07 20:06

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

查看更多
登录 后发表回答