使用lxml将节点从一个xml文件复制到另一个 [英] Copy a node from one xml file to another using lxml

查看:366
本文介绍了使用lxml将节点从一个xml文件复制到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到将一个节点复制到另一个XML文件的最简单方法.这两个文件将包含相同的节点-只是该节点的内容将不同.

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 (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()

这篇关于使用lxml将节点从一个xml文件复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆