如何解析 XML 并计算特定节点属性的实例? [英] How to parse XML and count instances of a particular node attribute?
问题描述
我在包含 XML 的数据库中有很多行,我正在尝试编写一个 Python 脚本来计算特定节点属性的实例.
I have many rows in a database that contains XML and I'm trying to write a Python script to count instances of a particular node attribute.
我的树看起来像:
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
如何使用 Python 访问 XML 中的属性 "1"
和 "2"
?
How can I access the attributes "1"
and "2"
in the XML using Python?
推荐答案
我建议 ElementTree
.相同 API 的其他兼容实现,例如 lxml
和 ElementTree
定义的 API.
I suggest ElementTree
. There are other compatible implementations of the same API, such as lxml
, and cElementTree
in the Python standard library itself; but, in this context, what they chiefly add is even more speed -- the ease of programming part depends on the API, which ElementTree
defines.
首先从 XML 构建一个 Element 实例 root
,例如使用 XML 函数,或通过使用以下内容解析文件:
First build an Element instance root
from the XML, e.g. with the XML function, or by parsing a file with something like:
import xml.etree.ElementTree as ET
root = ET.parse('thefile.xml').getroot()
或 ElementTree
.然后执行以下操作:
Or any of the many other ways shown at ElementTree
. Then do something like:
for type_tag in root.findall('bar/type'):
value = type_tag.get('foobar')
print(value)
和类似的,通常非常简单的代码模式.
And similar, usually pretty simple, code patterns.
这篇关于如何解析 XML 并计算特定节点属性的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!