如何使用python将一个xml节点的子节点插入另一个xml节点中

时间:2016-09-26 17:14:35

标签: python xml python-2.7

我有以下xml文件:

<root>
 <nodeA>
  <childrens_A>
 </nodeA>
 <nodeB>
  <childrens_B>
 </nodeB>
 <nodeA>
  <childrens_A>
 </nodeA>
 <nodeB>
  <childrens_B>
 </nodeB>
</root>

我想得到像

这样的东西
<root>
 <nodeA>
  <childrens_A>
  <childrens_B>
 </nodeA>
 <nodeA>
  <childrens_A>
  <childrens_B>
 </nodeA>
</root>

节点A和B的数量相等。 我只能从标准的python库导入。我无法导入lxml因为访问限制。所以我想限制from xml.etree import ElementTree as et

我的代码是:

from xml.etree import ElementTree as et
tree = et.parse(path_in)
root = tree.getroot()
for child in root.gethcildren()
  if child.tag == "nodeA"
     #insert children of nodeB in nodeA

tr.write(path_out)

提前致谢!

1 个答案:

答案 0 :(得分:0)

看起来我找到了解决方案:

from xml.etree import ElementTree as et

tr = et.parse(path_in)
    root = tr.getroot()
    for child in root.getchildren():
        if child.tag == 'nodeB':
            sub = child.getchildren()
            i = root.getchildren().index(child)
            root.getchildren()[i - 1].extend(sub)
tr.write(path_out)

希望一旦这个答案对某人有帮助。