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

2024-09-22 18:17:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下xml文件:

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

我想买点像

^{pr2}$

节点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)

提前谢谢!在


Tags: pathinfromimportchildtreeasroot
1条回答
网友
1楼 · 发布于 2024-09-22 18:17:45

看来我找到了解决办法:

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)

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

相关问题 更多 >