如何使用递增的计数器在XSLT中提供唯一的ID? [英] How to use an incremented counter to provide a unique id in XSLT?

查看:175
本文介绍了如何使用递增的计数器在XSLT中提供唯一的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XSLT将非常大的XML文档转换为(X)HTML。对于某些代码,我将它们转换为< div> 。我希望能够为这些标记创建唯一的id,使用递增的整数形成唯一id的一部分。

I am using XSLT to convert a very large XML document into (X)HTML. For some of the tags I am converting them to a <div>. I would like to be able to create a unique id for these tags, using an incremented integer to form part of the unique id.

我使用的规则的一个例子是:

An example of the rule I am using is:

<xsl:template match="bookcoll/book">
    <div class="book">
        <xsl:apply-templates/>
    </div>
</xsl:template>

这个XSLT模板运行良好。我现在想要的是标签:

This XSLT template is working nicely. What I would now like to have is the tag:

<div class="book">;  

成为:

<div class="book" id="book-[COUNTER-VALUE]">  

理想情况下,计数器将从1开始,而不是0。

Ideally the counter would start from 1, not 0.

我不知道它是否有很大的不同,我使用Java包javax.xml.parsers和javax.xml.transform来执行实际的转换。我是一个XSLT菜鸟,所以如果有任何我错过的相关信息请告诉我。

I don't know if it makes much difference, I am using the Java packages javax.xml.parsers and javax.xml.transform to perform the actual transformation. I am a bit of an XSLT noob, so if there's any pertinent information I've missed please let me know.

如何在XSLT中实现?

How could this be achieved in XSLT?

推荐答案

自然/惯用/故障安全解决方案将是:

The natural/idiomatic/failsafe solution would be:

<div class="book" id="book-{generate-id()}">

它没有递增,但它保证是唯一的。它将生成HTML有效的ID字符串(名称标记 )。

It's not incrementing, but it's guaranteed to be unique. And it's going to produce HTML-valid ID strings (name tokens).

编辑:如果必须递增,请执行以下操作:

If it must be incrementing, do something like the following:

<!-- in the calling template… -->
<xsl:apply-templates select="bookcoll/book[xpath to filter them if necessary]" />

<!-- …later -->
<xsl:template match="bookcoll/book">
  <div class="book" id="book-{position()}">
    <xsl:apply-templates/>
  </div>
</xsl:template>

您可以使用 format-number()根据您的需要调整 position()的输出。

You can use format-number() to adapt the output of position() to your needs.

position()将返回相对于当前正在处理的批处理的节点位置。通过显式调用< xsl:apply-templates> ,您可以确保它们按照您想要的方式编号。

position() will return the node position relative to the "batch" that is currently being processed. With an explicit call to <xsl:apply-templates> you make sure that they are numbered the way you want.

这篇关于如何使用递增的计数器在XSLT中提供唯一的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆