Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'lxml.etree._Element' object has no attribute 'write' ??? (PYTHON) [duplicate]

from lxml import etree

root = etree.Element('root1') 
element = etree.SubElement(root, 'element1')
root.write( 'xmltree.xml' ) 

Error:

AttributeError: 'lxml.etree._Element' object has no attribute 'write'

how can I fix this?

like image 999
Lucy Y. Avatar asked Mar 26 '13 10:03

Lucy Y.


People also ask

What is LXML Etree in Python?

The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API.


2 Answers

Elements (like root) do not have a write method, but ElementTrees do:

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

The documentation on tree.write is a little hard to find on the web. Here is the method's doc string:

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.
like image 140
unutbu Avatar answered Nov 15 '22 04:11

unutbu


If you are wanting to save your new xml to a file then etree.tostring is the method to use.

E.g.

>>> 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))
...
>>>
like image 35
MattH Avatar answered Nov 15 '22 04:11

MattH