在某些情况下,我在增加计数器时遇到了问题。
输入:
<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>要完成这一任务,可以使用以下算法:
- otherwise
- set counter to 1
因此,我尝试将其转换为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> 但是,通过执行此操作,我得到以下错误:
有什么想法吗?
发布于 2012-12-05 04:33:57
这个转换
<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>发布于 2012-12-05 08:44:23
在函数式编程语言中,“递增计数器”不是你要做的事情。您需要将所需的输出描述为输入的函数(正如Dimitre所做的那样),而不是描述用于计算输出的过程或过程。
https://stackoverflow.com/questions/13714647
复制相似问题