【发布时间】:2021-06-17 17:02:44
【问题描述】:
我已尝试查看与此类似的其他问题,但似乎没有人回答 xml.etree.ElementTree。
目前我的代码是这样的(它只是一个简单的 XML 生成器)
import xml.etree.ElementTree as ET
example1=ET.Element('example1')
example2=ET.SubElement(example1, 'example2').text='1234'
tree = ET.ElementTree(example1)
NewXML='example.xml'
tree.write(NewXML,encoding = 'UTF-8', xml_declaration = True)
目前的输出就是这个文件:
<?xml version='1.0' encoding='UTF-8'?>
<example1>
<example2>1234</example2>
</example1>
我想添加声明 Standalone = 'yes' 所以输出应该是:
<?xml version='1.0' encoding='UTF-8' standalone = 'yes'?>
<example1>
<example2>1234</example2>
</example1>
但这就是我遇到问题的地方。
我试过了
tree.write(NewXML,encoding = "UTF-8", xml_declaration = True, standalone = True)
tree.write(NewXML,encoding = "UTF-8", xml_declaration = True, standalone = "yes")
但我收到此错误:TypeError: write() got an unexpected keyword argument 'standalone'
【问题讨论】:
-
ElementTree 在
write()方法中没有standalone选项:docs.python.org/3/library/…。但是 lxml 可以:lxml.de/api/lxml.etree._ElementTree-class.html#write
标签: python xml elementtree xml-declaration