Lisa
Lisa

Reputation: 77

How to combine sibling elements into one using xslt

My xml excerpt is

    <p outputclass="figurecaption">Sections</p>
            <p outputclass="figure">
                <image href="9528.gif">
                    <alt></alt>
                </image>
</p>

I want it to transform into

<figure>
  <title>Sections</title>
  <graphic href="D:/9528.gif"/>
 </figure>

I am fairly new to xslt and have used identity transform to transform other elements in this xml. Can't seem to figure out this one.

Upvotes: 0

Views: 174

Answers (1)

Rudolf Yurgenson
Rudolf Yurgenson

Reputation: 603

This stylesheet transforms only adjacent (left to right) p[@outputclass='figurecaption'] and p[@outputclass='figure']

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes"/>

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

  <!-- process only those figure paragraphs that are immeditately preceded by figurecaption paragraph --> 
  <xsl:template match="p[@outputclass='figure'][preceding-sibling::*[1][self::p and @outputclass='figurecaption']]">
    <figure>
      <title><xsl:value-of select="preceding-sibling::p[1][@outputclass='figurecaption']"/></title>
      <graphic href="{image/@href}"/>
    </figure>
  </xsl:template>

  <!-- do nothing with figurecaption paragraph immediately followed by figure paragraph because if was processed in previous template -->
  <xsl:template match="p[@outputclass='figurecaption'][following-sibling::*[1][self::p and @outputclass='figure']]"/>

</xsl:stylesheet>

Upvotes: 1

Related Questions