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

Python中如何将已生成的XML变量写入保存为XML格式文件

解决方法

你已经通过dict2xml生成了格式正常的XML字符串,仅需补充文件写入逻辑即可完成保存,示例完整代码如下:

from dict2xml import dict2xml

# 替换为你自己的字典数据
my_dictionary = {
    "root": {
        "name": "测试数据",
        "value": 123
    }
}

xml = dict2xml(my_dictionary)
print(xml)

# 写入到XML文件
with open("output.xml", "w", encoding="utf-8") as file:
    file.write(xml)

注意事项

  • 写入时指定encoding="utf-8"可避免XML包含中文等非ASCII字符时出现乱码
  • 你可以将代码中的output.xml替换为自定义的保存路径和文件名
  • 如果你需要添加标准XML声明头,可调整写入部分的代码:
    with open("output.xml", "w", encoding="utf-8") as file:
        # 先写入XML声明
        file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        file.write(xml)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:39:01