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

Python中XML转字符串后声明消失,如何保留并导出?

如何让导出的XML文件保留版本声明?

我原本的XML文件开头带有<?xml version="1.0" encoding="utf-8"?>声明,但用xml.etree.ElementTree解析后转成字符串时,这个声明消失了。尝试手动在字符串前添加该声明,打印时能看到,但保存为XML文件后声明仍丢失。使用的代码如下:

import xml.etree.ElementTree as ET

tree = ET.parse(r'someData.xml')
root = tree.getroot()

xml_str = ET.tostring(root, encoding='unicode')
xml_str = '<?xml version="1.0" encoding="utf-8"?>' + xml_str

解决方案1:直接用ElementTree.write()保存(推荐)

无需手动拼接声明,调用write()方法时指定xml_declaration=True参数,即可自动在导出文件中添加声明:

import xml.etree.ElementTree as ET

tree = ET.parse(r'someData.xml')
# 保存时指定编码和声明参数
tree.write(r'output.xml', encoding='utf-8', xml_declaration=True)

执行后,output.xml开头会自动生成<?xml version='1.0' encoding='utf-8'?>声明。

解决方案2:先生成带声明的字符串再保存

如果需要先得到包含声明的字符串,再自行处理保存,不要用encoding='unicode'调用ET.tostring(),而是指定编码为utf-8并开启xml_declaration参数,生成字节串后再解码为字符串:

import xml.etree.ElementTree as ET

tree = ET.parse(r'someData.xml')
root = tree.getroot()

# 生成带声明的字节串,再解码为UTF-8字符串
xml_bytes = ET.tostring(root, encoding='utf-8', xml_declaration=True)
xml_str = xml_bytes.decode('utf-8')

# 写入文件
with open(r'output.xml', 'w', encoding='utf-8') as f:
    f.write(xml_str)

说明:之前手动拼接后保存仍丢失声明,大概率是因为保存文件时的编码配置错误,或是使用了非官方的XML处理方式导致声明被过滤。使用上述两种官方方法能确保声明被正确保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:31:02