2016-10-05 91 views
1

我是一个初学者,但有很大的力气,我想从所谓的“weather.xml” .xml文件看起来像这样解析有关天气的一些数据:解析XML天气与Python

<?xml version="1.0" encoding="UTF-8"?> 
<Weather> 
<locality name="Rome" alt="21"> 
    <situation temperature="18°C" temperatureF="64,4°F" humidity="77%" pression="1016 mb" wind="5 SSW km/h" windKN="2,9 SSW kn"> 
     <description>clear sky</description> 
     <lastUpdate>17:45</lastUpdate> 
     /> 
    </situation> 
    <sun sunrise="6:57" sunset="18:36" /> 
</locality> 

我从这个XML解析的一些数据,这是我的Python代码现在的样子:

#!/usr/bin/python 

from xml.dom import minidom 
xmldoc = minidom.parse('weather.xml') 

entry_situation = xmldoc.getElementsByTagName('situation') 
entry_locality = xmldoc.getElementsByTagName('locality') 

print entry_locality[0].attributes['name'].value 
print "Temperature: "+entry_situation[0].attributes['temperature'].value 
print "Humidity: "+entry_situation[0].attributes['humidity'].value 
print "Pression: "+entry_situation[0].attributes['pression'].value 

它的工作正常,但如果我尝试解析“说明”或者用同样的方法“LASTUPDATE”节点数据,我得到一个错误,所以对于那些实际上我可以看到它们是不同的节点,这种方式一定是错误的。

我也试图将输出写入日志文件没有成功,我得到的最多是一个空文件。

谢谢你的阅读时间。

+0

结束缺失。 7号线正在做什么?顺便说一句,你已经看过[lxml的objectify API](http://lxml.de/objectify.html)? – yegorich

+0

结束缺失,因为文件不停止,但有一部分我不在意从中检索数据。我在那里读过,但我不明白我如何根据我的使用情况调整代码。试图学习,但不是关于Python的知识,不幸的是 – antonioag

回答

1

这是因为“description”和“lastUpdate”不是属性,而是“情境”节点的子节点。

尝试:

d = entry_situation[0].getElementsByTagName("description")[0] 
print "Description: %s" % d.firstChild.nodeValue 

你应该使用相同的方法从其父“局部性”访问“风云”节点。

顺便说一句,你应该看看lxml模块,特别是yegorich说的客观化API。它更容易使用。

+0

它以这种方式工作,我对你表示非常感谢。它适用于“描述”,如果我为“lastUpdate”添加其他代码,它总是仅在“description”中向我显示“lastUpdate”。 – antonioag

+0

它不应该。我通过使用 'd = entry_situation [0] .getElementsByTagName(“description”)[0]' 'print“描述:%s”%d.firstChild.nodeValue' 'l = entry_situation [0] ] .getElementsByTagName(“lastUpdate”)[0]' 'print“上次更新:%s”%l.firstChild.nodeValue' –

+0

输出现在绝对没问题。我现在想要实现的是将“打印”内容传送到文件。我试着直接从shell使用这个命令:./script.py>它给了我一些ASCII错误,我通过写入代码“import codecs import locale import sys”和“sys.stdout = codecs .getwriter(locale.getpreferredencoding())(sys.stdout)“。它的工作原理,但我想实现的是追加到一个文件,并不总是覆盖它。如果我把一些代码直接从.py输出流,它会给出ASCII码错误。我想有TIMESTAMP +所有“打印”的东西 – antonioag