1.python 使用的xml.etree.elementtree库只支持解析和生成标准的utf-8格式的编码
2.常见GBK或GB2312等中文编码的 XML 文件,用以在老旧系统中保证 XML 对中文字符的记录能力
3.XML 文件开头有标识头,标识头指定了程序处理 XML 时应该使用的编码

4.要修改编码,不仅要修改文件整体的编码,还要将标识头中 encoding 部分的值修改
立即学习“Python免费学习笔记(深入)”;
1.读取&解码:
使用二进制模式读取 XML 文件,将文件变为二进制流
将二进制流使用.encode()方法,使用原文件的编码格式进行解析为字符串
2.处理标识头:使用.replace()方法,替换字符串中的encoding="xxx"部分
3.编码&保存:将字符串使用新的编码格式进行保存
GB2312 <–> UTF:无问题,可直接按照上面的逻辑处理
GBK <–> UTF8
GBK --> UTF8:无问题,可直接按照上面的逻辑处理
UTF8 --> GBK:.encode()会报错,要加上error="ignore"参数,忽略无法转换的字符
这里的原理是:GBK 编码兼容 UTF-8 编码,因此无法转换的内容使用 GBK 直接也能显示
GBK <–> GB2312:无问题
# filepath -- 原文件路径
# savefilepath -- 转换后文件存储路径(默认 = 原文件路径)
# oldencoding -- 原文件的编码格式
# newencoding -- 转换后文件的编码格式
def convert_xml_encoding(filepath, savefilepath=filepath, oldencoding, newencoding):
# Read the XML file
with open(filepath, 'rb') as file:
content = file.read()
# Decode the content from old encoding
# 出现错误时忽略 errors='ignore'
decoded_content = content.decode(oldencoding, errors='ignore')
# decoded_content = content.decode('GBK')
# Update the encoding in the XML header
updated_content = decoded_content.replace('encoding="{}"'.format(oldencoding),
'encoding="{}"'.format(newencoding))
# Encode the content to new encoding
# 出现错误时忽略 errors='ignore'
encoded_content = updated_content.encode(newencoding,errors='ignore')
# Write the updated content to the file
with open(savefilepath, 'wb') as file:
file.write(encoded_content)
# Result output
print(f"XML file '{os.path.basename(filepath)}'({oldencoding}) --> '{os.path.basename(savefilepath)}'({newencoding})")
# ---------------------- 使用示例 ---------------------
# GBK --> utf-8
convert_xml_encoding(filepath, savefilepath2, 'GBK', 'utf-8')
# utf-8 --> gb2312
convert_xml_encoding(filepath, savefilepath2, 'utf-8', 'gb2312')
# GBK --> gb2312
convert_xml_encoding(filepath, savefilepath2, 'GBK', 'gb2312')注意事项:
由于这里需要直接替换标识头,要求编码名称一定得完全匹配,否则替换会失败
如:GBK 不能写成 gbk,utf-8 不能写成 UTF8此代码仅在以上 GBK、GB2312、UTF-8 & 常用中英文基础上测试,其他的编码格式不保证一定能转换成功
以上就是Python中怎么对XML文件的编码进行转换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号