2012-01-18 73 views
1

希望对于那些有经验的人来说,这是一个快速的答案。我有一个XML文件,其中包含一个URL,我想从XML中获取URL,然后将其输入到我编写的下载器脚本中。我唯一的问题是我似乎无法正确解析XML中的URL。这看起来是这样的:Python - 从XML中解析单行文件

<program new-version="1.1.1.1" name="ProgramName"> 
<download-url value="http://website.com/file.exe"/> 
</program> 

在此先感谢!

回答

9
>>> 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

1
import lxml 
from lxml import etree 
et = etree.parse("your xml file or url") 
value = et.xpath('//download-url/@value') 
print "".join(value) 

输出= 'http://website.com/file.exe'

你也可以使用cssselect

f = open("your xml file",'r') 
values = f.readlines() 
values = "".join(values) 
import lxml.html 
doc = lxml.html.fromstring(values) 
elements = doc.cssselect('document program download-url') //csspath using firebug 
elements[0].get('value') 

输出= 'http://website.com/file.exe'