2024-04-19 02:01:41 发布
网友
我在一个包含XML的数据库中有很多行,我正试图编写一个Python脚本来计算特定节点属性的实例。
我的树看起来像:
<foo> <bar> <type foobar="1"/> <type foobar="2"/> </bar> </foo>
如何使用Python访问XML中的属性"1"和"2"?
"1"
"2"
我建议^{}。同一个API还有其他兼容的实现,比如Python标准库中的^{},和cElementTree;但是,在这种情况下,它们主要添加的是更高的速度——编程部分的易用性取决于ElementTree定义的API。
cElementTree
ElementTree
首先从XML构建一个元素实例root,例如使用XML函数,或者使用如下内容解析一个文件:
root
import xml.etree.ElementTree as ET root = ET.parse('thefile.xml').getroot()
或者在^{}中显示的任何其他方式。然后做如下事情:
for type_tag in root.findall('bar/type'): value = type_tag.get('foobar') print(value)
以及类似的,通常非常简单的代码模式。
^{}是最快、最直接的。
XML格式:
<data> <items> <item name="item1"></item> <item name="item2"></item> <item name="item3"></item> <item name="item4"></item> </items> </data>
Python:
from xml.dom import minidom xmldoc = minidom.parse('items.xml') itemlist = xmldoc.getElementsByTagName('item') print(len(itemlist)) print(itemlist[0].attributes['name'].value) for s in itemlist: print(s.attributes['name'].value)
输出:
4 item1 item1 item2 item3 item4
您可以使用BeautifulSoup:
from bs4 import BeautifulSoup x="""<foo> <bar> <type foobar="1"/> <type foobar="2"/> </bar> </foo>""" y=BeautifulSoup(x) >>> y.foo.bar.type["foobar"] u'1' >>> y.foo.bar.findAll("type") [<type foobar="1"></type>, <type foobar="2"></type>] >>> y.foo.bar.findAll("type")[0]["foobar"] u'1' >>> y.foo.bar.findAll("type")[1]["foobar"] u'2'
我建议^{} 。同一个API还有其他兼容的实现,比如Python标准库中的^{} ,和
cElementTree
;但是,在这种情况下,它们主要添加的是更高的速度——编程部分的易用性取决于ElementTree
定义的API。首先从XML构建一个元素实例
root
,例如使用XML函数,或者使用如下内容解析一个文件:或者在^{} 中显示的任何其他方式。然后做如下事情:
以及类似的,通常非常简单的代码模式。
^{} 是最快、最直接的。
XML格式:
Python:
输出:
您可以使用BeautifulSoup:
相关问题 更多 >
编程相关推荐