Python标准库xml.etree.ElementTree里的tostring()方法,可以把一个Element对象序列化为XML数据。这个方法提供了encoding参数,用来控制输出内容的编码格式和返回类型,理解它的行为对处理中文或对接外部系统很重要。

tostring()方法的基本用法
最基础的调用方式不传encoding,此时方法返回bytes类型,内容为UTF-8编码的XML。
import xml.etree.ElementTree as ET
root = ET.Element("root")
child = ET.SubElement(root, "item")
child.text = "中文内容"
# 默认返回UTF-8字节
data = ET.tostring(root)
print(type(data)) # <class 'bytes'>
print(data)
通过encoding参数控制编码
encoding参数既可以接收具体编码名称,也可以设为特殊值"unicode"。当传入如"gbk"、"utf-8"等编码名时,返回的是对应编码的bytes;当传入"unicode"时,返回的是str类型,内部按Python字符串存储,不再做字节编码。
指定具体编码输出字节
import xml.etree.ElementTree as ET
root = ET.Element("root")
child = ET.SubElement(root, "item")
child.text = "中文内容"
# 指定gbk编码,返回bytes
gbk_bytes = ET.tostring(root, encoding="gbk")
print(gbk_bytes)
# 指定utf-8并解码查看
utf8_bytes = ET.tostring(root, encoding="utf-8")
print(utf8_bytes.decode("utf-8"))
使用unicode获取字符串
import xml.etree.ElementTree as ET
root = ET.Element("root")
child = ET.SubElement(root, "item")
child.text = "中文内容"
# 返回str类型
xml_str = ET.tostring(root, encoding="unicode")
print(type(xml_str)) # <class 'str'>
print(xml_str)
XML声明头的差异
当encoding为具体编码且返回bytes时,tostring()会在开头生成对应的XML声明,例如<?xml version='1.0' encoding='gbk'?>。而使用encoding="unicode"返回字符串时,默认不会带XML声明,因为字符串本身无字节编码概念。
| encoding值 | 返回类型 | 是否带声明 |
|---|---|---|
| 不传或utf-8 | bytes | 是 |
| gbk等编码名 | bytes | 是 |
| unicode | str | 否 |
常见注意事项
- 如果要把结果写入文件,用bytes模式配合文件以wb打开,或用unicode模式配合w打开并指定文件编码。
- 包含中文时,不要误以为unicode模式返回乱码,它只是Python字符串,写入文件时需自行选编码。
- xml_declaration参数可配合控制是否输出声明,但仅对bytes模式有效。
简单说,控制tostring()编码的核心就是用好encoding参数:要字节选编码名,要字符串选unicode。
PythonElementTreetostring编码修改时间:2026-07-29 19:54:21