gpt4 book ai didi

xslt - 检查字符串长度并附加一个字符使其成为恒定长度

转载 作者:行者123 更新时间:2023-12-01 00:45:27 25 4
gpt4 key购买 nike

<Data>
<AA>123</AA>
<AA>45658</AA>
<AA>123456789</AA>
</Data>

需要的输出:

<info>
<Numbers id="000000123" />
<Numbers id="000045658" />
<Numbers id="123456789" />
</info>

条件:

我需要检查元素 AA 值的字符串长度。如果长度小于 9,我需要附加 '0' 使其长度为 9 位。

XSLT 写道:

<xsl:template match="Data">   
<info>
<xsl:for-each select="AA">
<Numbers>
<xsl:attribute name="id">
<xsl:variable name="numlenght">
<xsl:value-of select="string-length(.)" />
</xsl:variable>
<xsl:choose>
<xsl:when test="$numlenght&lt;9">
<xsl:variable name="balance">
<xsl:value-of select="9-$numlenght"/>
</xsl:variable>
<xsl:for-each select="//*[position() &lt;$balance]">
<xsl:value-of select="'0'"/>
</xsl:for-each>

</xsl:when>
</xsl:choose>
<xsl:value-of select="."/>

</xsl:attribute>
</Numbers>
</xsl:for-each>
</info>
</xsl:template>

我没有得到准确的输出。

谁能建议怎么做?

最佳答案

这需要更少的内存:

concat(substring('000000000', string-length() +1), .)

这是一个完整的转换:

<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="/*">
<info><xsl:apply-templates/></info>
</xsl:template>

<xsl:template match="AA">
<Numbers id="{concat(substring('000000000', string-length() +1), .)}"/>
</xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时:

<Data>
<AA>123</AA>
<AA>45658</AA>
<AA>123456789</AA>
</Data>

产生了想要的、正确的结果:

<info>
<Numbers id="000000123"/>
<Numbers id="000045658"/>
<Numbers id="123456789"/>
</info>

解释:

表达式:

concat(substring('000000000', string-length() +1), .)

不构造长度大于 9 的字符串(在另一个答案中,在此之后提取长度超过 9 个字符的字符串的子字符串)。

相比之下,它只提取填充 0 个字符所需的字符,然后将它们连接到当前节点的字符串值。

请注意:

这个:

  <Numbers id="{concat(substring('000000000', string-length() +1), .)}"/>

可以进一步简化为:

  <Numbers id="{substring('000000000', string-length() +1)}{.}"/>

关于xslt - 检查字符串长度并附加一个字符使其成为恒定长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12173041/

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