2011-11-23 64 views
1
from xml.dom.minidom import parseString, parse 

dom = parse('response.xml') 

xmlTag = dom.getElementsByTagName('link')[0].toxml() 

如何獲取XML的相對= 「候補」 的屬性 'href' 屬性:在Python,檢索XML屬性值

<link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=gfyKPbic&amp;feature=youtube_gdata'/> 
    <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gf7zhyKPbic/responses'/> 
+1

在其他錯誤,該行'DOM = parseString(data)dom = parse('response.xml')'是無效的Python語法。 – MattH

回答

3
DOC = """<root> 
    <link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=gfyKPbic&amp;feature=youtube_gdata'/> 
    <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gf7zhyKPbic/responses'/> 
</root>""" 
from xml.dom.minidom import parseString, parse 
dom = parseString(DOC) 
hreflist= [elt.getAttribute("href") for elt in dom.getElementsByTagName('link') if elt.getAttribute("rel")=="alternate"] 
for href in hreflist: 
    print(href)