基于SAP CPI的XSLT实现XML转指定JSON格式的问题求助
SAP CPI中XSLT Mapping实现XML转指定JSON的解决方案
问题1:将指定节点包装为JSON数组
当前代码仅能处理XML中重复出现的节点(如checks、checkFields)为数组,但单个节点(如emailIds、contactNumber、EICCaseDocuments、files)无法自动转为数组。需要在XSLT中明确指定这些节点,强制生成数组格式。
问题2:移除数字类型字段的引号
ClientId、PackageId、LegalEntityId、CheckId的值为数字,需要输出为JSON数值类型(不带引号)。通过匹配这些节点,直接输出其文本值而非包裹引号。
完整XSLT代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="UTF-8"/> <!-- 根节点处理 --> <xsl:template match="/root"> { <xsl:apply-templates select="*"/> } </xsl:template> <!-- 处理数字类型字段:ClientId、PackageId、LegalEntityId、CheckId --> <xsl:template match="ClientId|PackageId|LegalEntityId|CheckId"> "<xsl:value-of select="name()"/>" : <xsl:value-of select="."/> <xsl:if test="following-sibling::*">,</xsl:if> </xsl:template> <!-- 处理contactDetails节点,将子节点转为数组 --> <xsl:template match="contactDetails"> "<xsl:value-of select="name()"/>" : { "<xsl:value-of select="name(emailIds)"/>" : [ { <xsl:apply-templates select="emailIds/*"/> } ], "<xsl:value-of select="name(contactNumber)"/>" : [ { <xsl:apply-templates select="contactNumber/*"/> } ] } <xsl:if test="following-sibling::*">,</xsl:if> </xsl:template> <!-- 处理EICCaseDocuments节点为数组 --> <xsl:template match="EICCaseDocuments"> "<xsl:value-of select="name()"/>" : [ { <xsl:apply-templates select="*"/> } ] <xsl:if test="following-sibling::*">,</xsl:if> </xsl:template> <!-- 处理checks节点,包含内部files数组 --> <xsl:template match="checks"> "<xsl:value-of select="name()"/>" : [ <xsl:for-each select="."> { <xsl:apply-templates select="*[not(self::files)]"/> "<xsl:value-of select="name(files)"/>" : [ { <xsl:apply-templates select="files/*"/> } ] <xsl:if test="position() != last()">,</xsl:if> } </xsl:for-each> ] </xsl:template> <!-- 处理checkFields节点为数组 --> <xsl:template match="checkFields"> "<xsl:value-of select="name()"/>" : [ <xsl:for-each select="."> { <xsl:apply-templates select="*"/> } <xsl:if test="position() != last()">,</xsl:if> </xsl:for-each> ] <xsl:if test="following-sibling::*">,</xsl:if> </xsl:template> <!-- 通用节点处理:转为带引号的JSON字符串 --> <xsl:template match="*[not(self::ClientId|self::PackageId|self::LegalEntityId|self::CheckId|self::contactDetails|self::EICCaseDocuments|self::checks|self::checkFields)]"> "<xsl:value-of select="name()"/>" : "<xsl:value-of select="."/>" <xsl:if test="following-sibling::*">,</xsl:if> </xsl:template> </xsl:stylesheet>
关键代码说明
- 数字字段处理:通过精确匹配目标节点,直接输出文本值,不添加引号,实现JSON数值类型的输出。
- 数组节点处理:
- 对
contactDetails下的emailIds、contactNumber,强制用[]包裹生成数组 EICCaseDocuments和files节点同样强制转为数组结构,兼容XML中单个实例的场景checks和checkFields保留原有多实例数组逻辑,同时整合内部files节点的数组转换
- 对
- 通用节点处理:剩余节点默认转为带引号的JSON字符串,保证格式统一。
内容的提问来源于stack exchange,提问作者megrao1811
相关产品推荐
相关产品推荐

