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

Python中非标准XML转JSON的通用实现需求与问题

Python 非标准XML转通用JSON方案

核心思路

基于已解析的Schema结构,递归遍历XML值区域的元素,根据Schema定义的层级和多值规则,动态构建嵌套JSON结构——全程不硬编码块名,仅依赖Schema映射适配结构变更。

实现步骤与代码示例

1. 准备Schema映射

假设你已读取Schema并转换为如下结构(key为块名,value包含子块列表和多值标记):

# 示例Schema映射:is_multivalue=True表示允许多值(除Block1外均为True)
schema_map = {
    "Block1": {"children": ["Block2", "Block3"], "is_multivalue": False},
    "Block2": {"children": [], "is_multivalue": True},
    "Block3": {"children": ["Block3_1"], "is_multivalue": True},
    "Block3_1": {"children": [], "is_multivalue": True}
}

2. 递归转换函数

使用xml.etree.ElementTree解析XML,结合Schema映射递归处理嵌套结构:

import xml.etree.ElementTree as ET

def xml_to_json(element, schema):
    # 获取当前节点的Schema配置,默认多值
    node_conf = schema.get(element.tag, {"children": [], "is_multivalue": True})
    result = [] if node_conf["is_multivalue"] else {}

    # 处理子元素
    for child in element:
        child_data = xml_to_json(child, schema)
        if node_conf["is_multivalue"]:
            # 多值节点直接追加到列表
            result.append(child_data)
        else:
            # 单值节点按键值对存储,意外多值则转为列表
            if child.tag in result:
                if not isinstance(result[child.tag], list):
                    result[child.tag] = [result[child.tag]]
                result[child.tag].append(child_data)
            else:
                result[child.tag] = child_data

    # 处理节点文本(若存在有效内容)
    if element.text and element.text.strip():
        text_val = element.text.strip()
        if node_conf["is_multivalue"]:
            result.append(text_val)
        else:
            result = text_val

    # 空节点返回空列表(符合要求)
    if not result and node_conf["is_multivalue"]:
        return []
    return result

# 测试示例
xml_content = """
<Block1>
    <Block2>Value2-1</Block2>
    <Block2>Value2-2</Block2>
    <Block3>
        <Block3_1>Value3-1-1</Block3_1>
    </Block3>
    <Block3>
        <!-- 空Block3_1 -->
    </Block3>
</Block1>
"""

root = ET.fromstring(xml_content)
output = xml_to_json(root, schema_map)
print(output)

3. 关键逻辑说明

  • 多值处理:通过Schema的is_multivalue标记自动选择列表/字典存储,除Block1外所有块默认多值
  • 空块处理:无子元素且无文本的多值节点,自动返回空列表
  • 通用性:所有块名依赖Schema映射,结构或命名变更只需更新schema_map,无需修改转换逻辑
  • 文本兼容:处理节点内的纯文本内容,同时兼容嵌套结构

注意事项

  • 确保Schema映射的is_multivalue标记准确,严格区分单值/多值块
  • 解析XML时注意过滤空白文本,避免无效内容干扰结果
  • 若Schema包含更复杂的层级关联(如父节点约束),可扩展schema_map增加parent字段,进一步精准匹配XML嵌套关系

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:52:52