2020-11-24 23:23:05

XML

XML虽然比JSON复杂,在Web中应用也不如以前多了,不过仍有很多地方在用,所以,有必要了解如何操作XML。

DOM vs SAX

操作XML有两种方法:DOM和SAX。DOM会把整个XML读入内存,解析为树,因此占用内存大,解析慢,优点是可以任意遍历树的节点。SAX是流模式,边读边解析,占用内存小,解析快,缺点是我们需要自己处理事件。

正常情况下,优先考虑SAX,因为DOM实在太占内存。

在Python中使用SAX解析XML非常简洁,通常我们关心的事件是 start_element , end_element 和 char_data ,准备好这3个函数,然后就可以解析xml了。

举个例子,当SAX解析器读到一个节点时:

<a href="/">python</a>

会产生3个事件:

1. start_element事件,在读取 <a href=”/”> 时;
2. char_data事件,在读取 python 时;
3. end_element事件,在读取 </a> 时。

用代码实验一下:

from xml.parsers.expat import ParserCreate

class DefaultSaxHandler(object):
    def start_element(self, name, attrs):
        print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))
    
    def end_element(self, name):
        print('sax:end_element: %s' % name)
    
    def char_data(self, text):
        print('sax:char_data: %s' % text)

xml = r'''<?xml version="1.0"?>
<ol>
    <li><a href="/python">Python</a></li>
    <li><a href="/ruby">Ruby</a></li>
</ol>
'''

handler = DefaultSaxHandler() 
parser = ParserCreate()
parser.returns_unicode = True
parser.StartElementHandler = handler.start_element 
parser.EndElementHandler = handler.end_element 
parser.CharacterDataHandler = handler.char_data 
parser.Parse(xml)
C:\Users\Administrator\Desktop>python sax_xml.py
sax:start_element: ol, attrs: {}
sax:char_data:

sax:char_data:
sax:start_element: li, attrs: {}
sax:start_element: a, attrs: {u'href': u'/python'}
sax:char_data: Python
sax:end_element: a
sax:end_element: li
sax:char_data:

sax:char_data:
sax:start_element: li, attrs: {}
sax:start_element: a, attrs: {u'href': u'/ruby'}
sax:char_data: Ruby
sax:end_element: a
sax:end_element: li
sax:char_data:

sax:end_element: ol

C:\Users\Administrator\Desktop>

当设置 returns_unicode 为True时,返回的所有element名称和char_data都是unicode,处理国际化更方便。

需要注意的是读取一大段字符串时, CharacterDataHandler 可能被多次调用,所以需要自己保存起来,在 EndElementHandler 里面再合并。

除了解析XML外,如何生成XML呢?99%的情况下需要生成的XML结构都是非常简单的,因此,最简单也是最有效的生成XML的方法是拼接字符串:(伪代码)

L = []
L.append(r'<?xml version="1.0"?>')
L.append(r'<root>')
L.append(encode('some & data'))
L.append(r'</root>')
return ''.join(L)

如果要生成复杂的XML呢?建议你不要用XML,改成JSON。

解析XML时,注意找出自己感兴趣的节点,响应事件时,把节点数据保存起来。解析完毕后,就可以处理数据。

练习一下解析Yahoo的XML格式的天气预报,获取当天和最近几天的天气:

http://weather.yahooapis.com/forecastrss?u=c&w=2151330

参数 w 是城市代码,要查询某个城市代码,可以在weather.yahoo.com搜索城市,浏览器地址栏的URL就包含城市代码。

from xml.parsers.expat import  ParserCreate
weather_dict = {}
which_day = 0
class WeatherSaxHandler(object):
    def start_element(self,name,attrs):
        global  weather_dict,which_day
        if name=='yweather:location':
            weather_dict['city']=attrs['city']
            weather_dict['country'] = attrs['country']
 
        if name == 'yweather:forecast':
            which_day+=1
            if which_day == 1 :
                weather = {
                    'text':attrs['text'],
                    'low':int(attrs['low']),
                    'high':int(attrs['high'])
                }
                weather_dict['today'] = weather
            elif which_day == 2:
                weather={
                    'text': attrs['text'],
                    'low':int(attrs['low']),
                    'high':int(attrs['high'])
                }
                weather_dict['tomorrow'] = weather
 
    def char_data(self,name):
        pass
 
    def end_element(self,text):
        pass
 
def parse_weather(xml):
    wea = WeatherSaxHandler()
    parser = ParserCreate()
    parser.StartElementHandler = wea.start_element
    parser.EndElementHandler = wea.end_element
    parser.CharacterDataHandler = wea.char_data
    parser.Parse(xml)
    return weather_dict
 
data = r'''<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
    <channel>
        <title>Yahoo! Weather - Beijing, CN</title>
        <lastBuildDate>Wed, 27 May 2015 11:00 am CST</lastBuildDate>
        <yweather:location city="Beijing" region="" country="China"/>
        <yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/>
        <yweather:wind chill="28" direction="180" speed="14.48" />
        <yweather:atmosphere humidity="53" visibility="2.61" pressure="1006.1" rising="0" />
        <yweather:astronomy sunrise="4:51 am" sunset="7:32 pm"/>
        <item>
            <geo:lat>39.91</geo:lat>
            <geo:long>116.39</geo:long>
            <pubDate>Wed, 27 May 2015 11:00 am CST</pubDate>
            <yweather:condition text="Haze" code="21" temp="28" date="Wed, 27 May 2015 11:00 am CST" />
            <yweather:forecast day="Wed" date="27 May 2015" low="20" high="33" text="Partly Cloudy" code="30" />
            <yweather:forecast day="Thu" date="28 May 2015" low="21" high="34" text="Sunny" code="32" />
            <yweather:forecast day="Fri" date="29 May 2015" low="18" high="25" text="AM Showers" code="39" />
            <yweather:forecast day="Sat" date="30 May 2015" low="18" high="32" text="Sunny" code="32" />
            <yweather:forecast day="Sun" date="31 May 2015" low="20" high="37" text="Sunny" code="32" />
        </item>
    </channel>
</rss>
'''
if __name__ == "__main__":
    weather = parse_weather(data)
 
    assert weather['city'] == 'Beijing', weather['city']
    assert weather['country'] == 'China', weather['country']
    assert weather['today']['text'] == 'Partly Cloudy', weather['today']['text']
    assert weather['today']['low'] == 20, weather['today']['low']
    assert weather['today']['high'] == 33, weather['today']['high']
    assert weather['tomorrow']['text'] == 'Sunny', weather['tomorrow']['text']
    assert weather['tomorrow']['low'] == 21, weather['tomorrow']['low']
    assert weather['tomorrow']['high'] == 34, weather['tomorrow']['high']
    print('Weather:', str(weather))
C:\Users\Administrator\Desktop>python yahoo_weather.py
('Weather:', "{'city': u'Beijing', 'tomorrow': {'high': 34, 'text': u'Sunny', 'l
ow': 21}, 'today': {'high': 33, 'text': u'Partly Cloudy', 'low': 20}, 'country':
 u'China'}")

C:\Users\Administrator\Desktop>

By wanglei

发表评论