Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn element of lxml.objectify back into XML

Tags:

python

lxml

I use lxml.objectify to easily parse and work with an XML file. For auditing reasons, I have to save a derived object together with the originating XML code of the element.

root = lxml.objectify.fromstring(self.get_xml_data())

for i, elem in enumerate(root.elements):
    # create new database entry based on elem
    elem_obj.source_code = turn_elem_into_xml(elem)

How could I implement turn_elem_into_xml?

like image 567
Benjamin Wohlwend Avatar asked Feb 10 '12 16:02

Benjamin Wohlwend


People also ask

Is XML and lxml are same?

lxml is a reference to the XML toolkit in a pythonic way which is internally being bound with two specific libraries of C language, libxml2, and libxslt. lxml is unique in a way that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API.

What is objectify in lxml?

objectify through a custom Element implementation. The main idea is to hide the usage of XML behind normal Python objects, sometimes referred to as data-binding. It allows you to use XML as if you were dealing with a normal Python object hierarchy.

What is the use of lxml?

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers.

What is Etree in Python?

etree. ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.


2 Answers

lxml.etree.tostring

In [21]: r = lxml.objectify.fromstring('<root><item>1</item><item>2</item></root>')

In [22]: lxml.etree.tostring(r.item)
Out[22]: '<item>1</item>'
like image 171
reclosedev Avatar answered Sep 28 '22 09:09

reclosedev


lxml.objectify elements are still normal elements. You can print them like any other, or turn them into strings, using lxml.etree.tostring.

like image 22
Marcin Avatar answered Sep 28 '22 10:09

Marcin