【发布时间】:2014-05-11 10:49:37
【问题描述】:
我正在尝试使用 xml.etree.ElementTree 来解析一个 xml 文件,找到一个特定的标签,将一个子附加到该标签,将另一个子附加到新创建的标签,并将文本添加到后一个子。
我的 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' 的子级
像这样:
<root>
<a>
<b>
<c>test1</c>
</b>
<b>
<c>test2</c>
</b>
<b /><c/></a>
</root>
另外,如何向新创建的元素“c”添加文本?我可以遍历,直到找到没有文本但必须有更好的方法的标签“c”。
【问题讨论】:
标签: python xml xml-parsing elementtree