Discuss / Python / Homework

Homework

Topic source

大爷洒

#1 Created at ... [Delete] [Delete and Lock User]

Source:


class WeatherHandler(object):
    def __init__(self):
        self.current_data = ''
        self.city = ''
        self.forecast = []
        self.weather = {}

    def start_element(self, tag, attr):
        self.current_data = tag
        if tag == 'city':
            self.city = attr['name']

    def end_element(self, tag):
        if tag == 'forecast':
            self.forecast.append(self.weather)
            self.weather = {}
        self.current_data = ''

    def char_data(self, text):
        if self.current_data == 'date':
            self.weather['date'] = text
        elif self.current_data == 'high':
            self.weather['high'] = int(text)
        elif self.current_data == 'low':
            self.weather['low'] = int(text)

    def toJSON(self):
        d = {'city': self.city, 'forecast': self.forecast}
        return d

def parseXml(xml_str):
    # print(xml_str)
    parser = ParserCreate(encoding='utf-8')
    handler = WeatherHandler()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(xml_str)
    return handler.toJSON()


#test
url = 'http://127.0.0.1:8080/weather.xml'
with request.urlopen(url, timeout=4) as f:
    data = f.read()
result = parseXml(data.decode('utf-8'))
assert result['city'] == 'Beijing'
print(result,type(result),'ok')
print("----------------------------------")

XML Data


<?xml version="1.0"?>
<root>
    <city name='Beijing'>
        <forecast>
            <date>2017-11-17</date>
            <high>43</high>
            <low>26</low>           
        </forecast>
        <forecast>
            <date>2017-11-18</date>
            <high>41</high>
            <low>20</low>           
        </forecast>
        <forecast>
            <date>2017-11-19</date>
            <high>43</high>
            <low>19</low>           
        </forecast>
    </city>  
</root>

 Result:


{
    "city": "Beijing",
    "forecast": [{
        "date": "2017-11-17",
        "high": 43,
        "low": 26
    }, {
        "date": "2017-11-18",
        "high": 41,
        "low": 20
    }, {
        "date": "2017-11-19",
        "high": 43,
        "low": 19
    }]
}

  • 1

Reply