gpt4 book ai didi

python - 如何在 Python 中提取 XML 属性的值?

转载 作者:数据小太阳 更新时间:2023-10-29 02:03:32 24 4
gpt4 key购买 nike

我需要使用 Python 提取 XML 文档中的属性值。

例如,如果我有这样一个 XML 文档:

<xml>
<child type = "smallHuman"/>
<adult type = "largeHuman"/>
</xml>

我如何才能将文本“smallHuman”或“largeHuman”存储在变量中?

编辑:我是 Python 的新手,可能需要很多帮助。

这是我到目前为止尝试过的:

#! /usr/bin/python

import xml.etree.ElementTree as ET


def walkTree(node):
print node.tag
print node.keys()
print node.attributes[]
for cn in list(node):
walkTree(cn)

treeOne = ET.parse('tm1.xml')
treeTwo = ET.parse('tm3.xml')

walkTree(treeOne.getroot())

由于此脚本的使用方式,我无法将 XML 硬编码到 .py 文件中。

最佳答案

要从 XML 中获取属性值,您可以这样做:

import xml.etree.ElementTree as ET

xml_data = """<xml>
<child type = "smallHuman"/>
<adult type = "largeHuman"/>
</xml>"""

# This is like ET.parse(), but for strings
root = ET.fromstring(xml_data)

for a child in root:
print(child.tag, child.attrib)

您可以在下面的链接中找到更多详细信息和示例: https://docs.python.org/3.5/library/xml.etree.elementtree.html

关于python - 如何在 Python 中提取 XML 属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48746478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com