XSLT:将XML属性转换为XHTML类?

时间:2013-04-11 19:58:37

标签: xslt xpath

我有一个TEI XML文档,内容如下:

<said who="#Bernard">“I see a ring,” said Bernard, “hanging above
me.  It quivers and hangs in a loop of light.”</said>

<said who="#Susan">“I see a slab of pale yellow,” said Susan,
spreading away until it meets a purple stripe.”</said>

我想像这样输出XHTML:

<p class="Bernard">“I see a ring,” said Bernard, “hanging above
me.  It quivers and hangs in a loop of light.”</p>

<p class="Susan">“I see a slab of pale yellow,” said Susan,
spreading away until it meets a purple stripe.”</p>

将属性值映射到XHTML类的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

样式表

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" version="1.0" encoding="utf-8"/>

  <!-- Match root node -->
  <xsl:template match="/">
    <html>
      <body>
        <!-- Apply child nodes -->
        <xsl:apply-templates/>
      </body>
    </html>
  </xsl:template>

  <!-- Match <said> elements... -->
  <xsl:template match="said">
    <!-- ...and transform into <p> -->
    <p>
      <!-- Apply attributes and other child nodes -->
      <xsl:apply-templates select="@* | node()"/>
    </p>
  </xsl:template>

  <!-- Match @who attributes... -->
  <xsl:template match="@who">
    <!-- ...and transform into @class attributes -->
    <xsl:attribute name="class">
      <!-- Omit the hash mark -->
      <xsl:value-of select="substring(., 2)"/>
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>

输入

<waves>
  <said who="#Bernard">“I see a ring,” said Bernard, “hanging above
  me.  It quivers and hangs in a loop of light.”</said>

  <said who="#Susan">“I see a slab of pale yellow,” said Susan,
  spreading away until it meets a purple stripe.”</said>
</waves>

输出

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
  <p class="Bernard">“I see a ring,” said Bernard, “hanging above
  me.  It quivers and hangs in a loop of light.”</p>

  <p class="Susan">“I see a slab of pale yellow,” said Susan,
  spreading away until it meets a purple stripe.”</p>
</body></html>