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
?
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.
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.
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.
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.
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>'
lxml.objectify
elements are still normal elements. You can print them like any other, or turn them into strings, using lxml.etree.tostring
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With