簡體   English   中英

將一個etree的根代為另一個etree的元素

[英]Parent the root of an etree to the element of another etree

給定兩個元素樹,我想將其中一個的根插入另一個樹的某個元素中。 有任何想法嗎?

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM