我在某些条件下增加计数器时遇到问题。
输入:
<Users>
<User>
<id>1</id>
<username>jack</username>
</User>
<User>
<id>2</id>
<username>bob</username>
</User>
<User>
<id>3</id>
<username>bob</username>
</User>
<User>
<id>4</id>
<username>jack</username>
</User>
</Users>
想要的输出:
<Users>
<User>
<id>1</id>
<username>jack01</username>
</User>
<User>
<id>2</id>
<username>bob01</username>
</User>
<User>
<id>3</id>
<username>bob02</username>
</User>
<User>
<id>4</id>
<username>jack02</username>
</User>
</Users>
要完成此操作,可以使用以下算法:
- 按用户名对输入进行排序
- 对于每个用户
- 当以前的用户名等于当前用户名时
- 递增计数器和
- 将用户名设置为“$username$counter”
- 否则
- 将计数器设置为 1
- 当以前的用户名等于当前用户名时
- (再次按 ID 排序 - 并不是真正必要)
所以我尝试将其转换为 XSLT:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="Users">
<Users>
<xsl:apply-templates select="create_user">
<xsl:sort select="User/username"/>
</xsl:apply-templates>
</Users>
</xsl:template>
<xsl:template match="create_user">
<id><xsl:value-of select="id"/></id>
<xsl:choose>
<xsl:when test="username=(preceding-sibling::User[1]//username)">
<xsl:variable name="count">
<xsl:number format="01"/>
</xsl:variable>
<username><xsl:value-of select="concat(username, $count)"/></username>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="count">
<xsl:number value="1" format="01"/>
</xsl:variable>
<username><xsl:value-of select="concat(username, $count)"/></username>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
但是,通过执行此操作,我收到以下错误:
- 用户名不排序
- 计数器不增加
- 相反,当条件匹配时,计数器将是当前节点位置。
- 对于我们的示例,id = 3 的节点的用户名 = bob03
- 标签丢失
有什么想法吗?
最佳答案
这种转变:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="username/text()">
<xsl:value-of select="."/>
<xsl:value-of select=
"format-number(count(../../preceding-sibling::*[username=current()])+1,
'00')
"/>
</xsl:template>
</xsl:stylesheet>
应用于提供的 XML 文档时:
<Users>
<User>
<id>1</id>
<username>jack</username>
</User>
<User>
<id>2</id>
<username>bob</username>
</User>
<User>
<id>3</id>
<username>bob</username>
</User>
<User>
<id>4</id>
<username>jack</username>
</User>
</Users>
产生想要的正确结果:
<Users>
<User>
<id>1</id>
<username>jack01</username>
</User>
<User>
<id>2</id>
<username>bob01</username>
</User>
<User>
<id>3</id>
<username>bob02</username>
</User>
<User>
<id>4</id>
<username>jack02</username>
</User>
</Users>
关于templates - xslt 条件增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13714647/