2016-09-26 149 views
0

我已经follwing XML文件中插入一个XML节点的孩子在另一个XML节点:如何与Python

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

我想要得到的东西像节点A和B相等的

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

号码。 我只能从标准的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) 

谢谢!

+0

在您期望的结果中,您是否指节点B下的节点A下的''标记和节点B下的''标记?现在你正在重新安排不同父母下的孩子。 – Parfait

+0

我在nodeB下的预期结果。所以我想在NodeA中插入nodeB的子节点,然后删除空节点B –

回答

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) 

希望这一次的回答可以帮助到别人。

+0

但是,这只检查* nodeB *,而不检查其他节点。 – Parfait

+0

我只有nodeB,所以对我来说这就是答案。 对于多节点代码会稍微复杂一点 –