def parseWeatherResource(self, weatherResource): root = ET.fromstring(weatherResource) #root = tree.getroot() toDayWeather = None for weatherDOM in root: toDayWeather = Weather(year=weatherDOM.attrib['year'], month=weatherDOM.attrib['month'], day=weatherDOM.attrib['day'], hour=weatherDOM.attrib['hour']) localWeathers = [] for localDOM in weatherDOM: stnId = localDOM.attrib["stn_id"] desc = localDOM.attrib["desc"] ta = localDOM.attrib["ta"] localName = localDOM.text localWeather = LocalWeather(stdId=stnId, desc=desc, ta=ta, localName=localName) localWeathers.append(localWeather) toDayWeather.setLocalWeathers(localWeathers) return toDayWeather
class WeatherSAXHandler(xml.sax.ContentHandler): __weather = None __localWeathers = [] def __init__(self): xml.sax.ContentHandler.__init__(self) def startElement(self, name, attrs): if name == "weather": year = attrs.getValue('year') month = attrs.getValue('month') day = attrs.getValue('day') hour = attrs.getValue('hour') self.__weather = Weather(year=year, month=month, day=day, hour=hour) if name == "local": stnId = attrs.getValue('stn_id') descDOM = attrs.getValue('desc') taDOM = attrs.getValue('ta') self.dic = dict(stnId=stnId, desc=descDOM, ta=taDOM) def endElement(self, name): if name == 'local': stnId = self.dic['stnId'] desc = self.dic['desc'] ta = self.dic['ta'] localName = self.localName localWeather = LocalWeather(stnId, desc, ta, localName) self.__localWeathers.append(localWeather) elif name =='weather': self.__weather.setLocalWeathers(self.__localWeathers) def characters(self, content): self.localName = content def getWeatherInfo(self): return self.__weather
def startElement(self, name, attrs): if name == "weather": year = attrs.getValue('year') month = attrs.getValue('month') day = attrs.getValue('day') hour = attrs.getValue('hour') self.__weather = Weather(year=year, month=month, day=day, hour=hour) if name == "local": stnId = attrs.getValue('stn_id') descDOM = attrs.getValue('desc') taDOM = attrs.getValue('ta') self.dic = dict(stnId=stnId, desc=descDOM, ta=taDOM)
import xml.etree.ElementTree as ET from weather.dom.LocalWeather import LocalWeather from weather.dom.Weather import Weather if __name__ == '__main__': fileName = r"C:\workspace\WeatherXML\src\weather\source\sfc_web_map.xml" tree = ET.parse(fileName) root = tree.getroot() toDayWeather = None for weatherDOM in root: toDayWeather = Weather(year=weatherDOM.attrib['year'], month=weatherDOM.attrib['month'], day=weatherDOM.attrib['day'], hour=weatherDOM.attrib['hour']) localWeathers = [] for localDOM in weatherDOM: stnId = localDOM.attrib["stn_id"] desc = localDOM.attrib["desc"] ta = localDOM.attrib["ta"] tag = localDOM.tag localName = localDOM.text localWeather = LocalWeather(stdId=stnId, desc=desc, ta=ta, localName=localName) localWeathers.append(localWeather)