我在 XML 中有很多行,并且正在尝试获取特定节点属性的实例。
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
如何访问属性的值foobar
?在这个例子中,我想要"1"
and "2"
.
我建议ElementTree http://docs.python.org/library/xml.etree.elementtree.html。同一 API 还有其他兼容的实现,例如lxml https://lxml.de/parsing.html, and cElementTree
在 Python 标准库本身中;但是,在这种情况下,他们主要添加的是更快的速度——编程的难易程度取决于 API,这ElementTree
定义。
首先构建一个Element实例root
来自 XML,例如与XML http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.XML函数,或者通过解析文件,例如:
import xml.etree.ElementTree as ET
root = ET.parse('thefile.xml').getroot()
或者显示在以下位置的许多其他方式中的任何一种ElementTree http://docs.python.org/library/xml.etree.elementtree.html。然后做类似的事情:
for type_tag in root.findall('bar/type'):
value = type_tag.get('foobar')
print(value)
Output:
1
2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)