Jeff
Jeff

Reputation: 887

Merge matching elements attributes into single element

I have the following markup.

<para><span class="bidi"/><span class="ind"/>1</para>

I'm trying to achieve this...

<para><span style="direction:rtl; text-indent:10pt;">1</span></para>

However, I'm getting this...

<para><span style="direction:rtl">1</span><span style="text-indent:10pt">1</span></para>

Here is my XSLT.

  <xsl:template match="span" name="spans">
        <span>
            <xsl:attribute name="style">
        <xsl:choose>                
            <xsl:when test="@class eq 'bidi'">
                <xsl:text>direction:rtl</xsl:text>                
            </xsl:when>
            <xsl:when test="@class eq 'ind'">
                <xsl:text>text-indent:10pt;</xsl:text>                
            </xsl:when>
            <xsl:otherwise/>
        </xsl:choose>
            </xsl:attribute>
            <xsl:apply-templates/>
        </span>
    </xsl:template>

How do I merge the multiple spans into 1 with all of their class attribute values?

Upvotes: 2

Views: 865

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="para[span]">
     <para>
       <span>
          <xsl:attribute name="style">
           <xsl:apply-templates select="span"/>
          </xsl:attribute>
          <xsl:apply-templates select="node()[not(self::span)]"/>
       </span>
     </para>
 </xsl:template>

 <xsl:template match="span[@class='bidi']">
  <xsl:if test="position() >1"><xsl:text> </xsl:text></xsl:if>
  <xsl:text>direction:rtl;</xsl:text>
 </xsl:template>

 <xsl:template match="span[@class='ind']">
  <xsl:if test="position() >1"><xsl:text> </xsl:text></xsl:if>
  <xsl:text>text-indent:10pt;</xsl:text>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<para><span class="bidi"/><span class="ind"/>1</para>

produces the wanted, correct result:

<para><span style="direction:rtl; text-indent:10pt;">1</span></para>

Upvotes: 1

Related Questions