XML转JSON指定字段强制包裹方括号的XSLT转换问题
XSLT实现XML转指定格式JSON方案
转换规则
vpoItemList及其子字段vpoItemCsList无论对应行数据数量为1还是多条,必须始终用方括号包裹,输出为一维数组格式vpoShipDtlDtoGroupList与vpoShipDtlCsGroupList两个字段强制输出二维数组格式,其中vpoShipDtlCsGroupList要求每条行数据单独包裹一层方括号,最终结构为[[{...}],[{...}]]
完整XSLT 3.0转换代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet 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" version="3.0"> <xsl:output method="json" indent="yes" encoding="UTF-8"/> <xsl:template match="/"> <xsl:map> <!-- 处理vpoItemList 强制一维数组 --> <xsl:map-entry key="'vpoItemList'"> <xsl:variable name="items" select="Root/vpoItemList/vpoItem"/> <xsl:sequence select="array{ for $item in $items return map{ 'itemId': string($item/itemId), 'itemName': string($item/itemName), <!-- 其他vpoItem字段按需添加 --> 'vpoItemCsList': array{ for $cs in $item/vpoItemCsList/vpoItemCs return map{ 'csId': string($cs/csId), 'csValue': string($cs/csValue) <!-- 其他vpoItemCs字段按需添加 --> } } } }"/> </xsl:map-entry> <!-- 处理vpoShipDtlDtoGroupList 强制二维数组 --> <xsl:map-entry key="'vpoShipDtlDtoGroupList'"> <xsl:variable name="shipDtls" select="Root/vpoShipDtlDtoGroupList/vpoShipDtl"/> <xsl:sequence select="array{ for $dtl in $shipDtls return array{ map{ 'shipId': string($dtl/shipId), 'shipDate': string($dtl/shipDate) <!-- 其他vpoShipDtl字段按需添加 --> } } }"/> </xsl:map-entry> <!-- 处理vpoShipDtlCsGroupList 每条单独包数组的二维数组 --> <xsl:map-entry key="'vpoShipDtlCsGroupList'"> <xsl:variable name="csGroups" select="Root/vpoShipDtlCsGroupList/vpoShipDtlCs"/> <xsl:sequence select="array{ for $cs in $csGroups return array{ map{ 'csGroupId': string($cs/csGroupId), 'csGroupValue': string($cs/csGroupValue) <!-- 其他vpoShipDtlCs字段按需添加 --> } } }"/> </xsl:map-entry> <!-- 其他根级字段按需添加处理逻辑 --> </xsl:map> </xsl:template> </xsl:stylesheet>
使用说明
- 代码中
Root需替换为实际输入XML的根节点名称 - 各层级的字段映射可根据实际业务字段需求增删修改
- 本实现基于XSLT 3.0,需使用支持XSLT 3.0的解析器(如Saxon 9.8及以上版本)运行
内容的提问来源于stack exchange,提问作者raviteja
相关产品推荐
相关产品推荐

