You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WSO2 ESB如何移除包装将XML转为无嵌套JSON数组?

How to Get an Unwrapped JSON Array from Wrapped XML Conversion

我之前也碰到过类似的需求,想要跳过外层的Entries包装直接拿到纯Entry数组的JSON结果,有几种实用的办法可以实现:


方法一:先预处理XML(用XSLT去掉外层包装)

如果你的转换流程允许先处理XML,可以写一个简单的XSLT样式表,直接提取所有Entry节点,这样后续转JSON的时候自然就会生成无包装的数组:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/Entries">
    <xsl:copy-of select="Entry"/>
  </xsl:template>
</xsl:stylesheet>

用这个XSLT处理原XML后,得到的输出是多个独立的<Entry>节点集合,再转JSON就会直接输出:

[{"Customer": 1}, {"Customer": 2}]

方法二:转完JSON后直接提取数组(代码层面处理)

如果已经能生成带包装的JSON结果,最直接的方式就是在代码里提取Entry数组。这里给几个常见编程语言的示例:

JavaScript

// 假设已经得到带包装的JSON对象
const wrappedJson = {"Entries":{"Entry":[{"Customer": 1}, {"Customer": 2}]}};
// 直接提取Entry数组
const unwrappedArray = wrappedJson.Entries.Entry;
console.log(unwrappedArray); // 输出目标数组

Python(结合xmltodict工具)

import xmltodict
import json

# 原XML字符串
xml_content = '''<Entries> <Entry> <Customer>1</Customer> </Entry> <Entry> <Customer>2</Customer> </Entry> </Entries>'''
# XML转字典
parsed_data = xmltodict.parse(xml_content)
# 提取Entry数组并转成JSON
unwrapped_json = json.dumps(parsed_data['Entries']['Entry'])
print(unwrapped_json)

C#(用Newtonsoft.Json)

using Newtonsoft.Json.Linq;

string wrappedJson = @"{""Entries"":{""Entry"":[{""Customer"": 1}, {""Customer"": 2}]}}";
JObject jsonObj = JObject.Parse(wrappedJson);
// 提取Entry数组
JArray entryArray = (JArray)jsonObj["Entries"]["Entry"];
string unwrappedJson = entryArray.ToString();
// unwrappedJson就是你需要的无包装数组JSON

方法三:配置转换工具直接输出无包装数组

如果你使用的是专门的XML转JSON工具(比如Java的Jackson),可以通过配置跳过外层的Entries包装,直接获取Entry数组:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlToJsonConverter {
    public static void main(String[] args) throws Exception {
        String xml = "<Entries> <Entry> <Customer>1</Customer> </Entry> <Entry> <Customer>2</Customer> </Entry> </Entries>";
        XmlMapper xmlMapper = new XmlMapper();
        JsonNode rootNode = xmlMapper.readTree(xml);
        // 直接提取Entry节点数组
        JsonNode entryArray = rootNode.get("Entry");
        String unwrappedJson = xmlMapper.writeValueAsString(entryArray);
        System.out.println(unwrappedJson);
    }
}

内容的提问来源于stack exchange,提问作者Dreller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:47:48