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

如何用Python为每个OrderDetail生成独立XML文件?

解决方案

原代码会将所有<OrderDetail>节点的解压内容写入同一个文件导致覆盖,以下是修改后的代码,实现每个节点生成独立XML文件,并保留空行清理步骤:

修改后的完整代码

import xml.etree.ElementTree as ET
import base64
import zlib

tree = ET.parse('file.xml')
root = tree.getroot()
# 定义输出目录(若目录不存在需提前创建)
OUTPUT_DIR = "XMLparser"

def process_order_detail(detail_content, file_index):
    # 清理Base64文本中的换行/空格,避免解码错误
    cleaned_base64 = detail_content.strip()
    # 解码并解压内容
    decompressed_content = zlib.decompress(base64.b64decode(cleaned_base64), 16 + zlib.MAX_WBITS).decode('utf-8')
    # 生成独立文件名
    dest_file = f"{OUTPUT_DIR}/decompressed_{file_index}.xml"
    # 清理空行并写入文件
    with open(dest_file, 'w', encoding='utf-8') as file:
        # 过滤空行后重新拼接
        filtered_lines = [line for line in decompressed_content.splitlines() if line.strip()]
        file.write('\n'.join(filtered_lines))

def main():
    # 遍历所有OrderDetail节点,带索引区分
    for idx, child in enumerate(root.iter('OrderDetail'), start=1):
        process_order_detail(child.text, idx)

if __name__ == "__main__":
    main()

关键改动说明

  • 动态生成独立文件名:通过循环索引idx生成decompressed_1.xml、decompressed_2.xml这类文件名,彻底避免内容覆盖
  • 合并处理流程:将Base64解码、zlib解压、空行清理、文件写入整合为一个函数,减少重复IO操作,提升处理效率
  • 修复解码隐患:对<OrderDetail>节点文本调用strip(),去除XML中自带的换行和空格,避免Base64解码失败
  • 明确编码设置:写入文件时指定encoding='utf-8',避免不同环境下的编码乱码问题

内容的提问来源于stack exchange,提问作者a.cuko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:35:36