Saxon XSLT3中xml-to-json()生成未转义JSON的问题求助
解决Saxon XSLT 3.0 XML转JSON时的双重转义问题
你的问题根源在于对JSON输出做了双重序列化处理:
xml-to-json()函数已经将符合要求的map/array XML结构转换为JSON格式的字符串- 同时指定
method="json"的<xsl:result-document>会把这个字符串当成普通文本,再次进行JSON序列化,因此出现首尾引号和多余转义字符。
修复方案(二选一即可)
方案1:直接输出xml-to-json()生成的字符串
将<xsl:result-document>的method改为text,直接输出函数返回的JSON字符串,避免二次序列化:
<xsl:result-document href="{$target_json}" method="text"> <xsl:value-of select="xml-to-json($intermediate_XML, map{'indent':false() })"/> </xsl:result-document>
使用xsl:value-of而非xsl:copy-of更适合输出字符串类型的结果。
方案2:利用Saxon原生的JSON序列化能力
无需调用xml-to-json(),直接将符合http://www.w3.org/2005/xpath-functions命名空间的map/array节点输出到method="json"的结果文档中,Saxon会自动完成XML到JSON的转换:
<xsl:result-document href="{$target_json}" method="json" indent="no"> <xsl:copy-of select="$intermediate_XML"/> </xsl:result-document>
这里通过indent="no"参数实现原需求中indent:false()的效果。
两种方案都能生成你期望的无多余转义的JSON结果:
{ "headline" : "Matilda sold such dreadful ties", "body" : "\n<p>Matilda sold such dreadful ties.</p>\n<p>It made Juan retch and...</p>\n" }
内容的提问来源于stack exchange,提问作者Binsky
相关产品推荐
相关产品推荐

