简体   繁体   中英

LXML etree add existing (parsed) Element as SubElement to another (parsed) Element

I have two XML structures, xml_1 and xml_2

xml_1 is a structure that I have created as such:

xml_1 = etree.Element('xml_1_root')

xml_2 is a structure that I've parsed from existing XML data as such:

xml_2 = etree.parse(xml_2.xml).getroot()

I'd like to do something like this:

for node in xml_2.findall("node"):
    etree.SubElement(xml_1, node)

Such that all the structure from the node is added as a child to the newly-created xml_1 structure.

The issue, is that the SubElement method (obviously) doesn't work here, as it's unintended use.

My question is: Does the lxml.etree library have a method to add existing (parsed) Elements as SubElements such that any attributes, text, and child node information is preserved?

The issue is that many of the nodes in xml_2 have children (many of which also have children) and I'd rather avoid having to recurse into them to extract all the information granularly.

Note : This is not a question of how to create an etree SubElement from scratch. It's a question of how to add an existing Element to another tree while preserving the existing data structure.

I should have read the docs a bit more thoroughly.

The etree library provides the following method for a Element :

append(subelement) Adds the element subelement to the end of this element's internal list of subelements. Raises TypeError if subelement is not an Element.

So, to add an existing xml_2_node into the new xml_1 structure:

xml_1.append(xml_2_node)

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