在Python中获取Xml属性值

1 投票
1 回答
3153 浏览
提问于 2025-04-17 06:54
from xml.dom.minidom import parseString, parse

dom = parse('response.xml')

xmlTag = dom.getElementsByTagName('link')[0].toxml()
    <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'/>

我该如何获取xml中rel="alternate"的'href'属性呢?

1 个回答

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)

撰写回答