xsl中的XSL id()函数:数字计数

时间:2013-07-29 22:03:33

标签: xslt

在将XML转换为HTML时,我正在尝试将xref元素输出为带有自动生成的章节编号的链接,该章节编号是从外部参照引用的章节元素中提取的。

例如,使用这样的XML源文件:

<chapter id="a_chapter">
  <title>Title</title>
  <para>...as seen in <xref linkend="some_other_chapter">.</para>
</chapter>

<chapter id="some_other_chapter">
  <title>Title</title>
  <para>Some text here.</para>
</chapter>

其中有两章,外部参照引用第二章,生成的HTML中的外部参照应输出如下:

<section id="a_chapter">
  <h1>Title</h1>
  <p>...as seen in <a href="#some_other_chapter">Chapter 2</a>.</p>
</section>

但我不确定如何计算外部参照@linkend引用的章节元素。我尝试使用xsl:number,但我无法在count:

中使用id()函数
<xsl:template match="xref">

  <xsl:variable name="label">
    <xsl:when test="id(@linkend)[self::chapter]"><xsl:text>Chapter </xsl:text></xsl:when>
  </xsl:variable

  <xsl:variable name="count">
    <xsl:if test="id(@linkend)[self::chapter]"><xsl:number count="id(@linkend)/chapter" level="any" format="1"/></xsl:if>
  </xsl:variable>

  <a href="#{@linkend}">
    <xsl:value-of select="$label"/><xsl:value-of select="$count"/>
  </a>
</xsl:template>

我还尝试使用“chapter”作为xsl:number count的值,但是为所有输出生成了“Chapter 0”。

我离开这里,还是只是犯了一个愚蠢的xpath错误?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

在XSLT 1.0中,在调用<xsl:number>之前更改上下文:

<xsl:for-each select="id(@linkend)">
  <xsl:number/>
</xsl:for-each>

在XSLT 2.0中,使用select=属性更改上下文:

<xsl:number select="id(@linkend)"/>

答案 1 :(得分:0)

可能最简单的方法是使用chapter的模式模板来生成标签。

小例子......

XML输入

<doc>
    <chapter id="a_chapter">
        <title>Title</title>
        <para>...as seen in <xref linkend="some_other_chapter"/>.</para>
    </chapter>

    <chapter id="some_other_chapter">
        <title>Title</title>
        <para>Some text here.</para>
    </chapter>
</doc>

XSLT 1.0

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

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

    <xsl:template match="xref">
        <a href="#{@linkend}">
            <xsl:apply-templates select="/*/chapter[@id=current()/@linkend]" mode="label"/>
        </a>
    </xsl:template>

    <xsl:template match="chapter" mode="label">
        <xsl:text>Chapter </xsl:text>
        <xsl:number/>
    </xsl:template>

</xsl:stylesheet>

<强>输出

<doc>
   <chapter id="a_chapter">
      <title>Title</title>
      <para>...as seen in <a href="#some_other_chapter">Chapter 2</a>.</para>
   </chapter>
   <chapter id="some_other_chapter">
      <title>Title</title>
      <para>Some text here.</para>
   </chapter>
</doc>
相关问题