python - 使用 lxml 获取第一个元素的属性

标签 python lxml

尝试在 Python 中使用 lxml 解析 XML 文件,如何简单地获取元素属性的值?示例:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<item id="123">
    <sub>ABC</sub>
</item>

我想得到结果123,并将其存储为变量。

最佳答案

使用etree.parse()时,只需调用.getroot()即可获取根元素; .attrib 属性是所有属性的字典,使用它来获取值:

>>> from lxml import etree
>>> tree = etree.parse('test.xml')
>>> tree.getroot().attrib['id']
'123'

如果您使用etree.fromstring(),返回的对象已经是根对象,因此不需要.getroot()调用:

>>> tree = etree.fromstring('''\
... <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
... <item id="123">
...     <sub>ABC</sub>
... </item>
... ''')
>>> tree.attrib['id']
'123'

关于python - 使用 lxml 获取第一个元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029022/

相关文章:

python - 解析请求响应时应该使用 .text 还是 .content?

python - 最高负值

python - 求和多个python字典的对应元素

python - 使用 lxml 和 xpath 从 python ElementTree 中提取多个值

没有命名空间的 Python XpathEvaluator

python - 为什么这个 xpath 在 python 中使用 lxml 失败?

python - 在此 return 语句中使用 and 运算符

python - 使用 Django 减去 Web 服务器

Python 2.7.5 在 Ubuntu 上安装,MAXREPEAT

Python - 使用 lxml 将 urlib2 替换为 Requests