XSLT - Is it possible to output template matches into one span tag

时间:2017-06-09 12:41:38

标签: xslt xslt-1.0

The following is an XSLT Transform that outputs HTML. Is it possible to output both Target A and Target B into one span?

xsl

<xsl:template match="targetA | targetB">
   <span> Is it possible to output both targets in one span</span>
</xsl:template>

xml

<doc>
    <targetA>
        Target A Content
    </targetA>
    <targetB>
        Target B Content
    </targetB>
</doc>

expecting

<span>
Target A and Target B
</span>

1 个答案:

答案 0 :(得分:1)

This is similar to a previous question (Output once if both xml tags occur at the same time), so you can do this by having a template like this....

<xsl:template match="targetA | targetB[not(../targetA)]">
   <span> 
       <xsl:value-of select="../targetA" />
       <xsl:value-of select="../targetB" />
   </span>
</xsl:template>

(You would probably use an xsl:text if you wanted a space between then).

However, you would also need a template to match, and ignore targetB to avoid that being output again. (Assuming you are using the identity template, for example).

Try this XSLT...

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

    <xsl:template match="targetA | targetB[not(../targetA)]">
       <span> 
           <xsl:value-of select="../targetA" />
           <xsl:value-of select="../targetB" />
       </span>
    </xsl:template>

    <xsl:template match="targetB" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Note, this approach would fail if you have more that one targetA or targetB under the same parent.