>>> code = '''<program new-version="1.1.1.1" name="ProgramName">
... <download-url value="http://website.com/file.exe"/>
... </program>'''
随着lxml:
>>> import lxml.etree
>>> lxml.etree.fromstring(code).xpath('//download-url/@value')[0]
'http://website.com/file.exe'
随着内置xml.etree.ElementTree:
>>> import xml.etree.ElementTree
>>> doc = xml.etree.ElementTree.fromstring(code)
>>> doc.find('.//download-url').attrib['value']
'http://website.com/file.exe'
随着内置xml.dom.minidom:
>>> import xml.dom.minidom
>>> doc = xml.dom.minidom.parseString(code)
>>> doc.getElementsByTagName('download-url')[0].getAttribute('value')
u'http://website.com/file.exe'
在哪你选择完全取决于你。需要安装lxml,但它是速度最快,功能最丰富的库。 xml.etree.ElementTree有一个时髦的接口,它的XPath支持是有限的(取决于python标准库的版本)。 xml.dom.minidom不支持xpath,并且趋于较慢,但实现了交叉平台DOM。