简体   繁体   中英

Turn element of lxml.objectify back into XML

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.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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM