gpt4 book ai didi

xslt - 检查连续编号的属性

转载 作者:行者123 更新时间:2023-12-05 01:03:39 25 4
gpt4 key购买 nike

我有一种情况,我需要检查可能连续编号的属性值,并在开始值和结束值之间输入一个破折号。

<root>
<ref id="value00008 value00009 value00010 value00011 value00020"/>
</root>

理想的输出是...
8-11, 20

我可以将属性标记为单独的值,但我不确定如何检查“valueXXXXX”末尾的数字是否与前一个值连续。

我正在使用 XSLT 2.0

最佳答案

您可以使用 xsl:for-each-group@group-adjacent测试 number()值减去 position() .

这个技巧显然是由 David Carlisle 发明的, according to Michael Kay.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:output indent="yes"/>
<xsl:template match="/">
<xsl:variable name="vals"
select="tokenize(root/ref/@id, '\s?value0*')[normalize-space()]"/>

<xsl:variable name="condensed-values" as="item()*">

<xsl:for-each-group select="$vals"
group-adjacent="number(.) - position()">
<xsl:choose>
<xsl:when test="count(current-group()) > 1">
<!--a sequence of successive numbers,
grab the first and last one and join with '-' -->
<xsl:sequence select="
string-join(current-group()[position()=1
or position()=last()]
,'-')"/>
</xsl:when>
<xsl:otherwise>
<!--single value group-->
<xsl:sequence select="current-group()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</xsl:variable>

<xsl:value-of select="string-join($condensed-values, ',')"/>

</xsl:template>
</xsl:stylesheet>

关于xslt - 检查连续编号的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19459806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com