将etree的根作为另一个etree的元素

时间:2013-08-06 21:46:38

标签: python lxml elementtree

给定两个元素树,我想将其中一个的根插入到另一个元素的某个元素中。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

from xml.etree import ElementTree as et
t1 = et.parse('test1.xml')
t2 = et.parse('test2.xml')
t2.find('your/element').append(t1.getroot())
t2.write('test3.xml')

一个例子:

In [1]: from xml.etree import ElementTree as et
In [2]: !cat test1.xml
<el1>
  <el2></el2>
</el1>
In [3]: !cat test2.xml
<foo>
  <bar>
  </bar>
</foo>
In [4]: t1 = et.parse('test1.xml')
In [5]: t2 = et.parse('test2.xml')
In [6]: t2.find('bar').append(t1.getroot())
In [7]: t2.write('test3.xml')    
In [8]: !cat test3.xml
<foo>
  <bar>
  <el1>
  <el2 />
</el1></bar>
</foo>