我的意思是如何使用 ElementTree 将 MyBro 标签从双标签转换为单标签?
来自:
<MyBro>Steve</MyBro>
致:
<MyBro Name="Steve" />
附注问我做了什么?搜索文档和整个谷歌以获取信息。可能漏掉了什么?
我假设您正在解析 XML 文件/字符串,并且想要将具有双标记的节点替换为单标记。为此,以下解决方案应该有效。
import xml.etree.ElementTree as ET
XML = '''
<Friend>
<MyBro>
Foo
</MyBro>
<MyBro>
Bar
</MyBro>
<MyBro>
Lol
</MyBro>
</Friend>
'''
# tree = ET.parse(filename) # if XML from a file
tree = ET.ElementTree(ET.fromstring(XML))
root = tree.getroot()
ET.indent(root)
for child in root.findall('MyBro'):
name = child.text.strip() # get the name enclosed between two tags
tail = child.tail # record the original ordering
child.clear()
child.set('Name', name) # use attribute to store name
child.tail = tail # restore ordering
print(ET.tostring(root, encoding='unicode'))
输出将是
<Friend>
<MyBro Name="Foo" />
<MyBro Name="Bar" />
<MyBro Name="Lol" />
</Friend>