繁体   English   中英

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

[英]How to insert children of one xml node in another xml node with python

我有以下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)

提前致谢!

看起来我找到解决方案:

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)

希望这个答案能对别人有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM