问题
I have a xsl variable that has value
<p> <a href="https://www.google.com" target="_blank">Illustrating tips</a> </p>
How can I insert a css class to make the value of the variable, which will look like below. I also want to remove the paragraph tags.
<a href="https://www.google.com" target="_blank" class="titleClass">Illustrating tips</a>
回答1:
Assuming you have
<xsl:variable name="frag">
<p> <a href="https://www.google.com" target="_blank">Illustrating tips</a> </p>
</xsl:variable>
then use a mode
to transform it, e.g.
<xsl:template match="p" mode="m1">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="a[@href]" mode="m1">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="class">titleClass</xsl:attribute>
<xsl:apply-templates mode="m1"/>
</xsl:copy>
</xsl:template>
and
<xsl:variable name="transformed-frag">
<xsl:apply-templates select="$frag/node()" mode="m1"/>
</xsl:variable>
or directly where you want to output the result
<xsl:apply-templates select="$frag/node()" mode="m1"/>
If the a
element can contain more than plain text, you will need to add templates for them copying them in the mode, like a general identity transformation template or like an identity transformation template in that mode e.g.
<xsl:template match="@* | node()" mode="m1">
<xsl:copy>
<xsl:apply-templates select="@* | node()" mode="#current"/>
</xsl:copy>
</xsl:template>
来源:https://stackoverflow.com/questions/34279395/inserting-custom-css-class-into-a-xslt-variable