如何遍历XML内嵌JSON数组并转换为指定格式JSON?
问题描述
我有一段内嵌JSON数组的XML,结构如下:
<root> "countryList": [ { "countryName": "UK", "countryId": "909", "countryCapital": "london" }, { "countryName": "India", "countryId": "910", "countryCapital": "Delhi" } ] </root>
需要遍历其中的countryList数组,转换为指定结构的JSON输出:
{ "countries": [ { "Name": "UK", "Id": "909", "Capital": "london" }, { "Name": "India", "Id": "910", "Capital": "Delhi" } ] }
我尝试了以下XSLT代码但未成功,请求帮忙解决:
<xsl:text>{ countries: </xsl:text> <xsl: for-each = ="substring-before(substring-after(., '"countryList": '), ',')" > <xsl:text>{ Name: </xsl:text> <xsl:value-of select="substring-before(substring-after(., '"countryName": '), ',')"/> <xsl:text>, Id: </xsl:text> <xsl:value-of select="substring-before(substring-after(., '"countryId": '), ',')"/> <xsl:text>} </xsl:text> </xsl: for-each>
解决方案
核心思路:用XSLT 3.0原生JSON处理能力替代字符串截取
原代码依赖字符串截取处理JSON,不仅存在语法错误,还极易因为JSON格式的细微变化失效。XSLT 3.0内置了JSON解析和序列化功能,能可靠完成转换。
完整XSLT代码
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:array="http://www.w3.org/2005/xpath-functions/array"> <xsl:output method="json" indent="yes"/> <xsl:template match="/root"> <!-- 解析XML内的文本为JSON数据模型 --> <xsl:variable name="json-data" select="parse-json(.)"/> <!-- 构造目标JSON结构 --> <xsl:map> <xsl:map-entry key="'countries'"> <xsl:variable name="country-array" select="$json-data?countryList"/> <xsl:array> <!-- 遍历数组中的每个国家对象 --> <xsl:for-each select="array:members($country-array)"> <xsl:map> <xsl:map-entry key="'Name'" select=".?countryName"/> <xsl:map-entry key="'Id'" select=".?countryId"/> <xsl:map-entry key="'Capital'" select=".?countryCapital"/> </xsl:map> </xsl:for-each> </xsl:array> </xsl:map-entry> </xsl:map> </xsl:template> </xsl:stylesheet>
代码说明
- 解析JSON:
parse-json(.)将<root>节点内的文本内容直接解析为JSON的map/array结构,无需手动处理字符串 - 获取数组:
$json-data?countryList直接提取JSON中的countryList数组 - 遍历元素:
array:members($country-array)遍历数组中的每个国家对象 - 字段映射:将原JSON的
countryName、countryId、countryCapital分别映射为目标结构的Name、Id、Capital - 序列化输出:通过
<xsl:output method="json" indent="yes"自动生成格式正确的JSON,避免手动拼接的语法错误
原代码失败原因
xsl:for-each语法错误:多写了一个等号,且表达式无法正确定位数组元素- 字符串截取不可靠:依赖固定字符位置,JSON的换行、空格或字段顺序变化都会导致结果错误
- 手动拼接JSON易出错:缺少必要引号、逗号分隔逻辑不完善,生成的JSON可能不符合语法规范
内容的提问来源于stack exchange,提问作者Mohil M
相关产品推荐
相关产品推荐

