問(wèn)題描述
我正在嘗試使用 xml.etree.ElementTree 來(lái)解析一個(gè) xml 文件,找到一個(gè)特定的標(biāo)簽,將一個(gè)子附加到該標(biāo)簽,將另一個(gè)子附加到新創(chuàng)建的標(biāo)簽,并將文本添加到后一個(gè)子.
I am trying to use xml.etree.ElementTree to parse a xml file, find a specific tag, append a child to that tag, append another child to the newly created tag and add text to the latter child.
我的 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>
當(dāng)前代碼:
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' 的子級(jí)
This seems to work except 'c' appends as a child of 'a' rather then 'b'
像這樣:
<root>
<a>
<b>
<c>test1</c>
</b>
<b>
<c>test2</c>
</b>
<b /><c/></a>
</root>
另外,如何向新創(chuàng)建的元素c"添加文本?我可以遍歷,直到找到?jīng)]有文本但必須有更好的方法的標(biāo)簽c".
Also, how do I add text to the newly created element 'c'? I could iterate through until I find the a tag 'c' that has no text but there must be a better way.
推薦答案
需要指定b
作為c
的父元素.
You need to specify b
as a parent element for c
.
此外,為了獲取 a
標(biāo)記,您不需要循環(huán) - 只需獲取根 (a
).
Also, for getting the a
tag you don't need a loop - just take the root (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>
這篇關(guān)于python xml.etree.ElementTree 附加到子元素的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!