and*_*snn 8 python xml elementtree xml-parsing
我正在尝试使用xml.etree.ElementTree来解析xml文件,查找特定标记,将子项附加到该标记,将另一个子项附加到新创建的标记并将文本添加到后一个子项.
我的XML:
<root>
<a>
<b>
<c>text1</c>
</b>
<b>
<c>text2</c>
</b>
</a>
</root>
Run Code Online (Sandbox Code Playgroud)
期望的XML:
<root>
<a>
<b>
<c>text1</c>
</b>
<b>
<c>text2</c>
</b>
<b>
<c>text3</c>
</b>
</a>
</root>
Run Code Online (Sandbox Code Playgroud)
当前代码:
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
Run Code Online (Sandbox Code Playgroud)
这似乎有效,除了'c'作为'a'而不是'b'的孩子.
像这样:
<root>
<a>
<b>
<c>test1</c>
</b>
<b>
<c>test2</c>
</b>
<b /><c/></a>
</root>
Run Code Online (Sandbox Code Playgroud)
另外,如何将文本添加到新创建的元素"c"中?我可以迭代直到找到没有文字的标签'c',但必须有更好的方法.
ale*_*cxe 12
您需要指定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)
Run Code Online (Sandbox Code Playgroud)
打印:
<root>
<a>
<b>
<c>text1</c>
</b>
<b>
<c>text2</c>
</b>
<b>
<c>text3</c>
</b>
</a>
</root>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23456 次 |
| 最近记录: |