在XML声明python中编码

Nim*_*ims 8 python xml encoding declaration

我使用python创建了一个XML文件.但XML声明只有版本信息.如何使用XML声明包含编码,如:

<?xml version="1.0" encoding="UTF-8"?> 
Run Code Online (Sandbox Code Playgroud)

zol*_*i2k 6

>>> from xml.dom.minidom import Document
>>> a=Document()
>>> a.toprettyxml(encoding="utf-8")
'<?xml version="1.0" encoding="utf-8"?>\n'
Run Code Online (Sandbox Code Playgroud)

要么

>>> a.toxml(encoding="utf-8")
'<?xml version="1.0" encoding="utf-8"?>'
Run Code Online (Sandbox Code Playgroud)

您可以document.writexml()以相同的方式设置函数的编码.

  • 应该注意的是,当您传递“UTF-8”作为“encoding”参数时,“toprettyxml()”返回一个“bytes”对象。因此,当您写入文件时,必须使用“wb”选项打开它 with open("minidom_example.xml", "wb") as f: \n f.write(xml_str)` (2认同)