如何使用Python ElementTree提取xml属性 [英] How to extract xml attribute using Python ElementTree
本文介绍了如何使用Python ElementTree提取xml属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于:
<foo>
<bar key="value">text</bar>
</foo>
我如何获得价值?
xml.findtext("./bar[@key]")
引发错误。
推荐答案
这将找到名为 bar的元素的第一个实例
并返回属性 key
的值。
This will find the first instance of an element named bar
and return the value of the attribute key
.
In [52]: import xml.etree.ElementTree as ET
In [53]: xml=ET.fromstring(contents)
In [54]: xml.find('./bar').attrib['key']
Out[54]: 'value'
这篇关于如何使用Python ElementTree提取xml属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文