如何使用xslt将兄弟元素组合成一个元素

时间:2016-07-04 11:23:56

标签: xml xslt

我的xml摘录是

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

我希望它转变为

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

我对xslt相当新,并且使用了身份转换来转换此xml中的其他元素。似乎无法弄清楚这个。

1 个答案:

答案 0 :(得分:1)

此样式表仅转换邻近(从左到右)p [@ outputclass ='figurecaption']和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>