我正在尝试使用 xml.etree.ElementTree 来解析一个 xml 文件,找到一个特定的标签,将一个子附加到该标签,将另一个子附加到新创建的标签,并将文本添加到后一个子.
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>
当前代码:
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' 的子级
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>
另外,如何向新创建的元素c"添加文本?我可以遍历,直到找到没有文本但必须有更好的方法的标签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 标记,您不需要循环 - 只需获取根 (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>
这篇关于python xml.etree.ElementTree 附加到子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
使用 python 解析非常大的 xml 文件时出现问题Troubles while parsing with python very large xml file(使用 python 解析非常大的 xml 文件时出现问题)
使用 Python 2 在 XML 中按属性查找所有节点Find all nodes by attribute in XML using Python 2(使用 Python 2 在 XML 中按属性查找所有节点)
Python - 如何解析 xml 响应并将元素值存储在变量中Python - How to parse xml response and store a elements value in a variable?(Python - 如何解析 xml 响应并将元素值存储在变量中?)
如何在 Python 中获取 XML 标记值How to get XML tag value in Python(如何在 Python 中获取 XML 标记值)
如何使用 ElementTree 正确解析 utf-8 xml?How to correctly parse utf-8 xml with ElementTree?(如何使用 ElementTree 正确解析 utf-8 xml?)
将 XML 从 URL 解析为 python 对象Parse XML from URL into python object(将 XML 从 URL 解析为 python 对象)