网络编程
位置:首页>> 网络编程>> Python编程>> 浅谈python的elementtree模块处理中文注意事项

浅谈python的elementtree模块处理中文注意事项

作者:yuanchao99  发布时间:2021-06-17 12:02:46 

标签:python,elementtree,中文

处理中文在进行写文件时,必须采用以下方式:

tree.write(nxmlpath, "UTF-8")

如果写成:

tree.write(nxmlpath, "utf-8")

则会使输出文件缺少<?xml version="1.0" encoding="UTF-8"?>头

如果写成:

<?xml version="1.0" encoding="utf8"?>

则输出文件的中文不能被正常编码。

补充知识:Python ElementTree 导出 xml 缺少 开头声明

使用ElementTree修改完xml后,写入文件时,发现开头缺少了 <?xml version='1.0' encoding='utf-8'?>

解决办法:

在调用ElementTree的write方法写入xml时,参数里增加 encoding=‘utf-8' 以及 xml_declaration=True

et_root.write('file。xml', encoding='utf-8', xml_declaration=True)

来源:https://blog.csdn.net/yuanchao99/article/details/42010011

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com