5
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'

どうすればこれを修正できますか?

4

2 に答える 2

11

Elements(のようにroot)メソッドはありませんが、ElementTreeswriteにはメソッドがあります。

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は、Web上で見つけるのが少し難しいです。メソッドのドキュメント文字列は次のとおりです。

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.
于 2013-03-26T10:49:06.500 に答える
7

新しい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))
...
>>>
于 2013-03-26T10:37:27.140 に答える