XML转JSON时为Address行项强制嵌套数组的XSLT实现咨询
XML转JSON Address字段嵌套数组调整方案
你只需要调整XSLT中分组后的数组处理分支,为每一个Address行项单独包裹一层数组标签即可,调整后的完整代码如下:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="#all" xmlns="http://www.w3.org/2005/xpath-functions" expand-text="yes" version="3.0"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:variable name="json-xml"> <xsl:apply-templates/> </xsl:variable> <xsl:value-of select="xml-to-json($json-xml, map { 'indent' : true() })"/> </xsl:template> <xsl:template match="*[not(*)]"> <string key="{local-name()}">{.}</string> </xsl:template> <xsl:template match="*[(*) and . castable as xs:double]"> <number key="{local-name()}">{.}</number> </xsl:template> <xsl:template match="*[*]"> <xsl:param name="key" as="xs:boolean" select="false()"/> <map> <xsl:if test="$key"> <xsl:attribute name="key" select="local-name()"/> </xsl:if> <xsl:for-each-group select="*" group-by="node-name()"> <xsl:choose> <xsl:when test="current-group()[2] or self::Details or self::Address"> <array key="{local-name()}"> <xsl:choose> <xsl:when test="self::Details"> <array> <xsl:apply-templates select="current-group()"> <xsl:with-param name="key" select="false()"/> </xsl:apply-templates> </array> </xsl:when> <!-- 新增Address专属处理分支 --> <xsl:when test="self::Address"> <xsl:for-each select="current-group()"> <array> <xsl:apply-templates select="."> <xsl:with-param name="key" select="false()"/> </xsl:apply-templates> </array> </xsl:for-each> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="current-group()"> <xsl:with-param name="key" select="false()"/> </xsl:apply-templates> </xsl:otherwise> </xsl:choose> </array> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="current-group()"> <xsl:with-param name="key" select="true()"/> </xsl:apply-templates> </xsl:otherwise> </xsl:choose> </xsl:for-each-group> </map> </xsl:template> </xsl:stylesheet>
修改说明
- 在原有处理Details字段的分支后新增Address专属处理分支,遍历所有Address分组元素
- 为单个Address对象单独嵌套一层
<array>标签,最终生成"Address": [[{...}], [{...}]]的预期格式 - 原示例预期输出中JSON属性缺失逗号为书写疏漏,通过xml-to-json生成的结果会自动补全语法符号,输出合法JSON
内容的提问来源于stack exchange,提问作者raviteja
相关产品推荐
相关产品推荐

