我希望在将XML文档导入Python时能够选择要打印的节点
我正在使用python显示网站上托管的XML文件中的信息。我使用的代码如下:我希望在将XML文档导入Python时能够选择要打印的节点,python,xml,nodes,Python,Xml,Nodes,我正在使用python显示网站上托管的XML文件中的信息。我使用的代码如下: #IMPORTS from xml.dom import minidom import urllib #IMPORTING XML FILE xmldocurl = 'http://gamebattles.majorleaguegaming.com/ps4/call-of-duty-ghosts/team/TeamCrYpToNGamingEU/stats.xml' settings = urllib.urlopen
#IMPORTS
from xml.dom import minidom
import urllib
#IMPORTING XML FILE
xmldocurl = 'http://gamebattles.majorleaguegaming.com/ps4/call-of-duty-ghosts/team/TeamCrYpToNGamingEU/stats.xml'
settings = urllib.urlopen(xmldocurl).read()
final = minidom.parseString(settings)
date = final.getElementsByTagName('date')
for node in date:
test = node.getAttribute('timestamp')
print test
这将返回以下内容:
1411853400
1411850700
1411847100
1411843500
1411839000
1411837200
1411831800
1411828200
1411822800
1411820100
我只希望它返回标题“最近的匹配”下第一个节点的时间戳。这段代码现在返回所有称为timestamp的内容,但我只想要一个特定的
我怎么能选择这个
谢谢您需要获取recentMatches对象并查看第一次匹配的日期。一种方法是:
#IMPORTS
from xml.dom import minidom
import urllib
#IMPORTING XML FILE
xmldocurl = 'http://gamebattles.majorleaguegaming.com/ps4/call-of-duty-ghosts/team/TeamCrYpToNGamingEU/stats.xml'
settings = urllib.urlopen(xmldocurl).read()
final = minidom.parseString(settings)
recentMatches = final.getElementsByTagName('recentMatches')[0]
for node in recentMatches.childNodes:
if node.nodeName == "match":
nodes = node.getElementsByTagName('url')
print nodes[0].childNodes[0].data
nodes = node.getElementsByTagName('date')
print nodes[0].getAttribute('timestamp')
break
这将遍历匹配项并获得第一个日期时间戳。谢谢您的回答。如果我想在最近的匹配项下找到第一个URL,而不是第一个时间戳,那该怎么做呢?基本上,你会对
URL
元素而不是date
元素执行相同的代码。我做了:recentMatches=final.getElementsByTagName('recentMatches'))对于recentMatches中的match:date_node=match.getElementsByTagName('match')timestamp=date_node[0]。getAttribute('url')打印时间戳中断
,返回了一个空白。你知道这是为什么吗?Thanks@crossboy007我已经更新了代码,已经有一段时间没有编写XMl了。基本上,您是在迭代匹配,当您有一个匹配节点时,您可以访问url
和date
元素(每个元素应该有一个)。