‘lxml.etree._Element’对象没有属性’write’??? (PYTHON)

参见英文答案 > 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))
...
>>>
上一篇:python – 获取lxml中特定名称的所有节点?


下一篇:在Fedora上运行python脚本时没有名为lxml.html的模块