ElementTree的tostring()默认返回UTF-8 bytes,不支持直接指定GBK等编码;需用write()+BytesIO配合encoding参数才能正确生成带匹配声明的非UTF-8 XML内容。

ElementTree 的 tostring() 方法默认返回 bytes(字节串),编码为 UTF-8,**不支持直接通过参数指定其他编码**。若要得到指定编码的字符串(比如 GBK、ISO-8859-1)或避免字节解码问题,需分两步处理:先用 tostring() 得到 bytes,再手动解码;或者改用 write() 配合 BytesIO + 指定 encoding。
方法一:tostring() 后手动解码(推荐用于简单场景)
tostring() 默认输出 UTF-8 字节,你可以显式解码成 str,或按需重新编码为其他格式(注意:XML 声明中的 encoding 属性需同步更新,否则可能不合法):
- 获取 UTF-8 字符串:
tostring(root, encoding='utf-8').decode('utf-8') - 想输出 GBK 字符串?先 tostring 得 bytes,再 decode 成 str,但注意:XML 声明必须匹配,例如
——tostring()不自动改声明,需手动替换或避免写声明 - 如果只要 bytes 且指定编码(如 GBK),不能直接传
encoding='gbk'给tostring()(会报错或被忽略),只能自己 encode:tostring(root, encoding='utf-8').decode('utf-8').encode('gbk')(不推荐,易出乱码)
方法二:用 write() + BytesIO(精准控制 encoding 和 XML 声明)
这是更可靠的方式,尤其需要非 UTF-8 编码或确保 XML 声明正确时:
- 创建
BytesIO对象 - 调用
tree.write(buffer, encoding='gbk', xml_declaration=True) - 从 buffer 中读取 bytes 或解码为 str
- 示例:
from io import BytesIO
buffer = BytesIO()
tree.write(buffer, encoding='gbk', xml_declaration=True)
result_bytes = buffer.getvalue() # b'... '
result_str = result_bytes.decode('gbk') # 正确解码为字符串
注意 encoding 参数在 tostring() 中的实际行为
tostring(elem, encoding=...) 的 encoding 参数只接受 'utf-8'、'us-ascii'、'unicode'(Python 2/3 兼容写法)或 None。传入 'gbk' 会触发 ValueError: Unicode error 或静默回退——它**不是通用编码开关**,而是限定输出类型:
立即学习“Python免费学习笔记(深入)”;
-
encoding='unicode'或encoding=None→ 返回str(即 Unicode 字符串,不含 BOM,无 XML 声明) -
encoding='utf-8'(默认)→ 返回bytes -
encoding='us-ascii'→ 返回bytes,非 ASCII 字符会被字符引用(如你)
总结:怎么选
要可读字符串且不关心编码细节 → 用 tostring(..., encoding='unicode');
要生成带正确 encoding 声明的 GBK/GBK2312 等文件内容 → 用 write() + BytesIO;
要调试或快速看结构 → 直接 print(tostring(root)),它会自动 decode 成 str(Python 3 中)。
基本上就这些,不复杂但容易忽略 encoding 的实际约束范围。










