参见英文答案 > Write xml file using lxml library in Python 3个
from lxml import etree
root = etree.Element('root1')
element = etree.SubElement(root, 'element1')
root.write( 'xmltree.xml' )
错误:
AttributeError: 'lxml.etree._Element' object has no attribute 'write'
我怎样才能解决这个问题?
解决方法:
如果您想将新的xml保存到文件中,则etree.tostring是要使用的方法.
例如.
>>> from lxml import etree
>>> root = etree.Element('root1')
>>> element = etree.SubElement(root, 'element1')
>>> print etree.tostring(root,pretty_print=True) ## Print document
<root1>
<element1/>
</root1>
>>> with open('xmltree.xml','w') as f: ## Write document to file
... f.write(etree.tostring(root,pretty_print=True))
...
>>>