当前位置: 代码迷 >> python >> 如何在 Python 中提取 XML 属性的值?
  详细解决方案

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

热度:72   发布时间:2023-07-16 11:04:51.0

我需要使用 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 文件中。

使用 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']

输出:

smallHuman
largeHuman

要从 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)

您可以在以下链接中找到更多详细信息和示例: :

另一个使用 lxml 库的例子:

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

from lxml import etree as et

root = et.fromstring(xml)

# find attribute using xpath
child_type = root.xpath('//xml/child/@type')[0]
print(child_type)

adult_type = root.xpath('//xml/adult/@type')[0]
print(adult_type)

# combination of find / get
child_type = root.find('child').get('type')
adult_type = root.find('adult').get('type')

print(child_type)
print(adult_type)

另一个使用 SimplifiedDoc 库的例子:

from simplified_scrapy import SimplifiedDoc, utils
xml = '''<xml>
    <child type = "smallHuman"/>
    <adult type = "largeHuman"/>
</xml>'''
doc = SimplifiedDoc(xml).select('xml')

# first
child_type = doc.child['type']
print(child_type)

adult_type = doc.adult['type']
print(adult_type)

# second
child_type = doc.select('child').get('type')
adult_type = doc.select('adult').get('type')

print(child_type)
print(adult_type)

# second
child_type = doc.select('child>type()')
adult_type = doc.select('adult>type()')

print(child_type)
print(adult_type)

# third
nodes = doc.selects('child|adult>type()')
print(nodes)
# fourth
nodes = doc.children
print ([node['type'] for node in nodes])