简体   繁体   English

将lxml.objectify的元素转换回XML

[英]Turn element of lxml.objectify back into XML

I use lxml.objectify to easily parse and work with an XML file. 我使用lxml.objectify轻松解析和使用XML文件。 For auditing reasons, I have to save a derived object together with the originating XML code of the element. 出于审计原因,我必须将派生对象与元素的原始XML代码一起保存。

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 ? 我怎样才能实现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. lxml.objectify元素仍然是普通元素。 You can print them like any other, or turn them into strings, using lxml.etree.tostring . 您可以像使用lxml.etree.tostring一样打印它们,或者将它们转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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