我需要使用 Python 提取 XML 文档中的属性值。
例如,如果我有一个这样的 XML 文档:
<xml>
<child type = "smallHuman"/>
<adult type = "largeHuman"/>
</xml>
Run Code Online (Sandbox Code Playgroud)
我如何才能将文本“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())
Run Code Online (Sandbox Code Playgroud)
由于此脚本的使用方式,我无法将 XML 硬编码到 .py 文件中。
使用 ElementTree,您可以使用find 方法和attrib。
例子:
import xml.etree.ElementTree as ET
z = """<xml>
<child type = "smallHuman"/>
<adult type = "largeHuman"/>
</xml>"""
treeOne = ET.fromstring(z)
print treeOne.find('./child').attrib['type']
print treeOne.find('./adult').attrib['type']
Run Code Online (Sandbox Code Playgroud)
输出:
smallHuman
largeHuman
Run Code Online (Sandbox Code Playgroud)
小智 5
要从 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)
Run Code Online (Sandbox Code Playgroud)
您可以在以下链接中找到更多详细信息和示例:https : //docs.python.org/3.5/library/xml.etree.elementtree.html