Python 中对 XML 文件的编码转换问题

1. 在 Python 中 XML 文件的编码问题

1.Python 使用的xml.etree.ElementTree库只支持解析和生成标准的UTF-8格式的编码

2.常见GBKGB2312等中文编码的 XML 文件,用以在老旧系统中保证 XML 对中文字符的记录能力

3.XML 文件开头有标识头,标识头指定了程序处理 XML 时应该使用的编码

在这里插入图片描述

4.要修改编码,不仅要修改文件整体的编码,还要将标识头中 encoding 部分的值修改

2. 处理 Python XML 文件的思路

1.读取&解码:

  • 使用二进制模式读取 XML 文件,将文件变为二进制流
  • 将二进制流使用.encode()方法,使用原文件的编码格式进行解析为字符串

2.处理标识头:使用.replace()方法,替换字符串中的encoding="xxx"部分

3.编码&保存:将字符串使用新的编码格式进行保存

3. 实际过程中遇到的问题

  • GB2312 <–> UTF:无问题,可直接按照上面的逻辑处理
  • GBK <–> UTF8
    • GBK --> UTF8:无问题,可直接按照上面的逻辑处理
    • UTF8 --> GBK:.encode()会报错,要加上error="ignore"参数,忽略无法转换的字符
    • 这里的原理是:GBK 编码兼容 UTF-8 编码,因此无法转换的内容使用 GBK 直接也能显示
  • GBK <–> GB2312:无问题

4. 最后使用的代码

# 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, savefilepath1, 'GBK', 'utf-8')
# utf-8 --> gb2312
convert_xml_encoding(filepath, savefilepath1, 'utf-8', 'gb2312')
# GBK --> gb2312
convert_xml_encoding(filepath, savefilepath1, 'GBK', 'gb2312')

注意事项:

  • 由于这里需要直接替换标识头,要求编码名称一定得完全匹配,否则替换会失败
  • 如:GBK 不能写成 gbk,utf-8 不能写成 UTF8此代码仅在以上 GBK、GB2312、UTF-8 & 常用中英文基础上测试,其他的编码格式不保证一定能转换成功
作者:Lilixxs原文地址:https://blog.csdn.net/weixin_44112083/article/details/129646255

%s 个评论

要回复文章请先登录注册