You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XSLT 1.0中将整数类型的profileid转换为字符串?

在XSLT 1.0中将整数值转换为字符串的解决方案

你在使用XSLT 1.0处理profileid整数元素时,需要将其值以字符串形式传递给后续流程。当前的XSLT代码转换XML后再转JSON时,profileId输出为数字类型,而你期望它是带引号的字符串类型。

当前使用的XSLT代码:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="no" method="xml"/>
    <xsl:template match="/">
          <Session>
            <xsl:variable name="profileID" select="concat(' ',$profileid)"/>
            <profileId>
                <xsl:value-of select="translate($profileID,' ','')"/>
            </profileId>
        </Session>
    </xsl:template>
</xsl:stylesheet>

当前JSON输出:

{ "Session": { "profileId": 452628 } }

期望的JSON输出:

{ "Session": { "profileId": "452628" } }

可以通过两种简单的方式在XSLT 1.0中显式将整数值转换为字符串:

方法1:使用concat()函数拼接空字符串

XSLT 1.0中concat()函数会将所有参数转换为字符串后拼接,因此只需将目标数值与空字符串拼接,即可得到字符串类型的结果:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="no" method="xml"/>
    <xsl:template match="/">
          <Session>
            <profileId>
                <xsl:value-of select="concat('', $profileid)"/>
            </profileId>
        </Session>
    </xsl:template>
</xsl:stylesheet>

方法2:使用string()函数直接转换

string()函数可以将任何类型的值转换为字符串类型,直接对$profileid使用该函数即可:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="no" method="xml"/>
    <xsl:template match="/">
          <Session>
            <profileId>
                <xsl:value-of select="string($profileid)"/>
            </profileId>
        </Session>
    </xsl:template>
</xsl:stylesheet>

原理说明

这两种方式的核心都是显式将数值类型转换为字符串类型。原代码中直接输出数值时,后续的XML转JSON工具会识别为数字;而转换为字符串后,工具会保留引号,将其处理为JSON字符串类型。

内容的提问来源于stack exchange,提问作者stels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:00:16