我正在创建一个 xml
文件,我只希望它应该在顶部显示这个
<?xml version="1.0" encoding="utf-8"?>
现在它只说
<?xml version="1.0" ?>
这就是我创建它的方式。
xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ")
with open("Test.xml", "w", encoding='utf-8') as f:
f.write(xmlstr)
最佳答案
添加encoding
参数即可:
xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ", encoding="utf-8")
将保存文件中的“w”改为“wb”。
并且,如评论中所建议的那样,将虚假解析丢弃回 XML:
from lxml import etree
xml_object = etree.tostring(root,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8')
然后将xml_object
写入文件即可。
关于python - 添加 "encoding="utf-8"?> 到 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68921881/