使用XSLT Mediator转换XML为JSON时结果被text字段包裹的问题
解决XSLT Mediator转换JSON被包裹在text字段的问题
核心问题分析
你的问题本质是XSLT输出的JSON被当作XML文本节点处理,导致Mediator将其包装到text字段中。要解决这个问题,需要从XSLT的输出结构和配置入手,避免生成多余的XML包装节点。
具体修正方案
方案1:直接输出纯JSON文本(适用于XSLT 2.0+)
如果你的XSLT是通过序列化生成JSON字符串,不要用任何XML元素(比如<text>)包裹输出内容,同时设置输出方法为text:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:json="http://www.w3.org/2005/xpath-functions/json"> <!-- 设置输出为纯文本,避免XML结构干扰 --> <xsl:output method="text" encoding="UTF-8"/> <xsl:template match="/"> <!-- 直接输出序列化后的JSON,不要嵌套在XML节点里 --> <xsl:value-of select="json:serialize(your-xml-to-json-mapping)"/> </xsl:template> </xsl:stylesheet>
方案2:使用Mediator识别的JSON映射XML结构(部分ESB产品约定)
部分XSLT Mediator要求通过特定的XML节点(如jsonObject/jsonArray)来生成JSON,而非纯文本。这种情况下,直接构建对应结构即可:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <!-- 用jsonObject节点定义顶层对象,Mediator会直接转换为JSON对象 --> <jsonObject> <name><xsl:value-of select="root/user/name"/></name> <age><xsl:value-of select="root/user/age"/></age> <hobbies> <!-- 用jsonArray定义数组 --> <jsonArray> <xsl:for-each select="root/user/hobbies/hobby"> <item><xsl:value-of select="."/></item> </xsl:for-each> </jsonArray> </hobbies> </jsonObject> </xsl:template> </xsl:stylesheet>
方案3:XSLT 3.0原生JSON输出
如果支持XSLT 3.0,直接设置输出方法为json,并通过xsl:sequence输出JSON序列化结果:
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:json="http://www.w3.org/2005/xpath-functions/json"> <!-- 直接指定输出为JSON格式 --> <xsl:output method="json" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <xsl:sequence select="json:serialize(your-xml-node, map{'method':'json'})"/> </xsl:template> </xsl:stylesheet>
验证示例
- 当前错误输出:
{"text": "{\"name\":\"John\",\"age\":30,\"hobbies\":[\"reading\",\"coding\"]}"}
- 修正后期望输出:
{"name":"John","age":30,"hobbies":["reading","coding"]}
内容的提问来源于stack exchange,提问作者Some Guy
相关产品推荐
相关产品推荐

