Copy a node from one xml file to another using lxml

这一生的挚爱 提交于 2020-01-03 05:29:04

问题


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

回答1:


Here's one way - its not brilliant as it loses the position (i.e. 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()


来源:https://stackoverflow.com/questions/24705052/copy-a-node-from-one-xml-file-to-another-using-lxml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!