2014-03-31 101 views
5

我想使用xml.etree.ElementTree來解析一個xml文件,找到一個特定的標籤,追加一個孩子到該標籤,追加另一個孩子到新創建的標籤,並添加文字給後者的孩子。python xml.etree.ElementTree追加到子元素

我的XML:

<root> 
<a> 
    <b> 
     <c>text1</c> 
    </b> 
    <b> 
     <c>text2</c> 
    </b> 
</a> 
</root>  

期望中的XML:

<root> 
<a> 
    <b> 
     <c>text1</c> 
    </b> 
    <b> 
     <c>text2</c> 
    </b> 
    <b> 
     <c>text3</c> 
    </b> 
</a> 
</root> 

當前代碼:

import xml.etree.ElementTree as ET 
tree = ET.parse('test.xml') 
root = tree.getroot() 


for x in root.iter(): 
    if (x.tag == 'a'): 
     ET.SubElement(x, 'b') 
     ET.SubElement(x, 'c') 
     #add text 

這似乎除了 'c' 的工作追加爲孩子 'A'而不是'b'

Li ke so:

<root> 
<a> 
    <b> 
     <c>test1</c> 
    </b> 
    <b> 
     <c>test2</c> 
    </b> 
    <b /><c/></a> 
</root> 

另外,如何向新創建的元素'c'添加文本?我可以迭代,直到找到沒有文本的標籤'c',但必須有更好的方法。

回答

7

您需要指定b作爲c的父元素。

此外,爲了獲得a標籤,您不需要循環 - 只需取根(a)。

import xml.etree.ElementTree as ET 

tree = ET.parse('test.xml') 
root = tree.getroot() 

a = root.find('a') 
b = ET.SubElement(a, 'b') 
c = ET.SubElement(b, 'c') 
c.text = 'text3' 

print ET.tostring(root) 

打印:

<root> 
    <a> 
     <b> 
      <c>text1</c> 
     </b> 
     <b> 
      <c>text2</c> 
     </b> 
     <b> 
      <c>text3</c> 
     </b> 
    </a> 
</root> 
+0

如果'a'是一個孩子,然後我需要循環找到'a'? – andrsnn

+0

@ user2210274 nope,那麼就使用'root.find('a')'。 – alecxe

+0

我應該更具體一些,'一個'不是根。我會修改我的問題。 – andrsnn

1

我喜歡定義自己的功能添加文本:

def SubElementWithText(parent, tag, text): 
    attrib = {} 
    element = parent.makeelement(tag, attrib) 
    parent.append(element) 
    element.text = text 
    return element 

,然後是儘可能使用起來非常方便:

import xml.etree.ElementTree as ET 

tree = ET.parse('test.xml') 
root = tree.getroot() 

a = root.find('a') 
b = ET.SubElement(a, 'b') 
c = SubElementWithText(b, 'c', 'text3')