xml.etree.ElementTree 将 xml 文件中的双标签转换为单标签

问题描述 投票:0回答:1

我的意思是如何使用 ElementTree 将 MyBro 标签从双标签转换为单标签?

来自:

<MyBro>Steve</MyBro>

致:

<MyBro Name="Steve" />

附注问我做了什么?搜索文档和整个谷歌以获取信息。可能漏掉了什么?

python-3.x xml elementtree
1个回答
0
投票

我假设您正在解析 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>
© www.soinside.com 2019 - 2024. All rights reserved.