簡體   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