XSLT - 相对于祖先添加数字属性

时间:2016-02-14 23:32:32

标签: xslt

我想检索原始xml文档的副本,其中每个节点都有一个添加的number属性,这些属性不会与父节点相关,而是与祖先相关。转换,例如:

<collection>
   <poem>
     <head>THE RAVEN.</head>
     <stanza>
      <l>ONCE upon a midnight dreary, while I pondered, weak and weary,</l>
      <l>Over many a quaint and curious volume of forgotten lore,</l>
      <l>While I nodded, nearly napping, suddenly there came a tapping,</l>
      <l>As of some one gently rapping, rapping at my chamber door.</l>
      <l>“ ‘Tis some visiter,” I muttered, “tapping at my chamber door —</l>
      <l>Only this, and nothing more.”</l>
    </stanza>
    <stanza>
      <l>Ah, distinctly I remember it was in the bleak December,</l>
      <l>And each separate dying ember wrought its ghost upon the floor.</l>
      ...
    </stanza>
   </poem>
   <poem>
     ...
   </poem>
</collection>

成:

 <collection>
   <poem>
     <head>THE RAVEN.</head>
     <stanza n="1">
      <l n="1">ONCE upon a midnight dreary, while I pondered, weak and weary,</l>
      <l n="2">Over many a quaint and curious volume of forgotten lore,</l>
      <l n="3">While I nodded, nearly napping, suddenly there came a tapping,</l>
      <l n="4">As of some one gently rapping, rapping at my chamber door.</l>
      <l n="5">“ ‘Tis some visiter,” I muttered, “tapping at my chamber door —</l>
      <l n="6">Only this, and nothing more.”</l>
    </stanza>
    <stanza n="2">
      <l n="7">Ah, distinctly I remember it was in the bleak December,</l>
      <l n="8">And each separate dying ember wrought its ghost upon the floor.</l>
      ...
    </stanza>
   </poem>
   <poem>
     ...
   </poem>
</collection>

即。从诗的祖先而不是节中计算每一行。

我似乎无法正确使用xsl:number函数。提前谢谢。

1 个答案:

答案 0 :(得分:0)

假设您要重新开始每个poem的计数,请尝试:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="stanza | l">
    <xsl:copy>
        <xsl:attribute name="n">
            <xsl:number from="poem" level="any"/>
        </xsl:attribute>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

删除from属性以在整个文档中连续计数。