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事件,在讀取``時;
2. char_data事件,在讀取`python`時;
3. end_element事件,在讀取``時。
用代碼實驗一下:
~~~
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.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)
~~~
需要注意的是讀取一大段字符串時,`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時,注意找出自己感興趣的節點,響應事件時,把節點數據保存起來。解析完畢后,就可以處理數據。
### 練習
請利用SAX編寫程序解析Yahoo的XML格式的天氣預報,獲取當天和第二天的天氣:
[http://weather.yahooapis.com/forecastrss?u=c&w=2151330](http://weather.yahooapis.com/forecastrss?u=c&w=2151330)
參數`w`是城市代碼,要查詢某個城市代碼,可以在[weather.yahoo.com](https://weather.yahoo.com/)搜索城市,瀏覽器地址欄的URL就包含城市代碼。
~~~
# -*- coding:utf-8 -*-
from xml.parsers.expat import ParserCreate
# 測試:
data = r'''
Yahoo! Weather - Beijing, CN
Wed, 27 May 2015 11:00 am CST
39.91
116.39
Wed, 27 May 2015 11:00 am CST
'''
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))
~~~
?Run
### 參考源碼
[use_sax.py](https://github.com/michaelliao/learn-python3/blob/master/samples/commonlib/use_sax.py)
- 關于
- Python簡介
- 安裝Python
- Python解釋器
- 第一個Python程序
- 使用文本編輯器
- Python代碼運行助手
- 輸入和輸出
- Python基礎
- 數據類型和變量
- 字符串和編碼
- 使用list和tuple
- 條件判斷
- 循環
- 使用dict和set
- 函數
- 調用函數
- 定義函數
- 函數的參數
- 遞歸函數
- 高級特性
- 切片
- 迭代
- 列表生成式
- 生成器
- 迭代器
- 函數式編程
- 高階函數
- 返回函數
- 匿名函數
- 裝飾器
- 偏函數
- 模塊
- 使用模塊
- 安裝第三方模塊
- 面向對象編程
- 類和實例
- 訪問限制
- 繼承和多態
- 獲取對象信息
- 實例屬性和類屬性
- 面向對象高級編程
- 使用slots
- 使用@property
- 多重繼承
- 定制類
- 使用枚舉類
- 使用元類
- 錯誤、調試和測試
- 錯誤處理
- 調試
- 單元測試
- 文檔測試
- IO編程
- 文件讀寫
- StringIO和BytesIO
- 操作文件和目錄
- 序列化
- 進程和線程
- 多進程
- 多線程
- ThreadLocal
- 進程 vs. 線程
- 分布式進程
- 正則表達式
- 常用內建模塊
- datetime
- collections
- base64
- struct
- hashlib
- itertools
- XML
- HTMLParser
- urllib
- 常用第三方模塊
- PIL
- virtualenv
- 圖形界面
- 網絡編程
- TCP/IP簡介
- TCP編程
- UDP編程
- 電子郵件
- SMTP發送郵件
- POP3收取郵件
- 訪問數據庫
- 使用SQLite
- 使用MySQL
- 使用SQLAlchemy
- Web開發
- HTTP協議簡介
- HTML簡介
- WSGI接口
- 使用Web框架
- 使用模板
- 異步IO
- 協程
- asyncio
- aiohttp
- 實戰
- Day 1 - 搭建開發環境
- Day 2 - 編寫Web App骨架
- Day 3 - 編寫ORM
- Day 4 - 編寫Model
- Day 5 - 編寫Web框架
- Day 6 - 編寫配置文件
- Day 7 - 編寫MVC
- Day 8 - 構建前端
- Day 9 - 編寫API
- Day 10 - 用戶注冊和登錄
- Day 11 - 編寫日志創建頁
- Day 12 - 編寫日志列表頁
- Day 13 - 提升開發效率
- Day 14 - 完成Web App
- Day 15 - 部署Web App
- Day 16 - 編寫移動App
- FAQ
- 期末總結