简体   繁体   中英

Copy a node from one xml file to another using lxml

I'm trying to find the simplest way of copying one node to another XML file. Both files will contain the same node - just the contents of that node will be different.

In the past I've done some crazy copying of each element and subelement - but there has to be a better way..

#Master XML
parser = etree.XMLParser(strip_cdata=False)
tree = etree.parse('file1.xml', parser)
# Find the //input node - which has a lot of subelems
inputMaster= tree.xpath('//input')[0]

#Dest XML - 
parser2 = etree.XMLParser(strip_cdata=False)
tree2 = etree.parse('file2.xml', parser2)
# this won't work but.. it would be nice
etree.SubElement(tree2,'input') = inputMaster

Here's one way - its not brilliant as it loses the position (ie it pops the node at the end) but hey..

    def getMaster(somefile):
       parser = etree.XMLParser(strip_cdata=False)
       tree = etree.parse(somefile, parser)
       doc = tree.getroot()
       inputMaster =  doc.find('input')
       return inputMaster

     inputXML = getMaster('master_file.xml')
     parser = etree.XMLParser(strip_cdata=False)
     tree = etree.parse('file_to_copy_node_to.xml', parser)
     doc = tree.getroot()
     doc.remove(doc.find('input'))
     doc.append(inputXML)   
     # Now write it
     newxml = etree.tostring(tree, pretty_print=True)
     f = open('file_to_copy_node_to.xml', 'w')
     f.write(newxml)
     f.close()

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