【问题标题】:'lxml.etree._Element' object has no attribute 'write' ??? (PYTHON) [duplicate]'lxml.etree._Element' 对象没有属性 'write' ??? (Python)[重复]
【发布时间】:2013-03-16 02:26:06
【问题描述】:
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'

我该如何解决这个问题?

【问题讨论】:

  • @Mark:还记得吗?

标签: python lxml elementtree


【解决方案1】:

Elements(如root)没有write 方法,但ElementTrees 有:

from lxml import etree

root = etree.Element('root1') 
element = etree.SubElement(root, 'element1')
tree = root.getroottree()
print(type(tree))
# <type 'lxml.etree._ElementTree'>
tree.write('xmltree.xml') 

tree.write 上的文档在网络上有点难找到。这是该方法的文档字符串:

In [7]: tree.write?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:    <built-in method write of lxml.etree._ElementTree object at 0x95c48cc>
Namespace:  Interactive
Docstring:
    write(self, file, encoding=None, method="xml",
              pretty_print=False, xml_declaration=None, with_tail=True,
              standalone=None, compression=0,
              exclusive=False, with_comments=True)

    Write the tree to a filename, file or file-like object.

    Defaults to ASCII encoding and writing a declaration as needed.

    The keyword argument 'method' selects the output method:
    'xml', 'html', 'text' or 'c14n'.  Default is 'xml'.

    The ``exclusive`` and ``with_comments`` arguments are only
    used with C14N output, where they request exclusive and
    uncommented C14N serialisation respectively.

    Passing a boolean value to the ``standalone`` option will
    output an XML declaration with the corresponding
    ``standalone`` flag.

    The ``compression`` option enables GZip compression level 1-9.

【讨论】:

    【解决方案2】:

    如果您想将新的 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))
    ...
    >>>
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2018-07-10
      • 1970-01-01
      • 2022-11-13
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多