关于python用SAX解析XML

        XML即可扩展标记语言(Extensible Markup Language 其被设计为传输和存储数据,其焦点是数据的内容。 而熟悉的HTML则是 被设计用来显示数据,其焦点是数据的外观。

       python里面操作XML有两种方法:DOM和SAX。

       DOM会把整个XML读入内存,解析为树,因此占用内存大,解析慢,优点是可以任意遍历树的节点。

       SAX是流模式,边读边解析,占用内存小,解析快,缺点是我们需要自己处理事件。

       但是由于DOM太占内存所以一般采用SAX。

       用SAX解析XML文件的时候我们通常只用关注三个件:start_element(读取标签头),end_element(读取标签尾)以及char_data(标签中间的内容)


比如要从这段xml代码里面获取到获取当天和第二天的天气

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>
'''
from xml.parsers.expat import ParserCreate
class A(object):
  def __init__(self):
    self._data = {}
    self._count = 0
  def get_data(self):
    return self._data
  def start_element(self,name,attrs):
    if name == 'yweather:location':
      self._data['city'] = attrs['city']
      self._data['country'] = attrs['country']
    elif name == 'yweather:forecast':
      if self._count == 0:
        self._data['today'] = {}
        self._data['today']['text'] = attrs['text']
        self._data['today']['low'] = attrs['low']
        self._data['today']['high'] = attrs['high']
        self._count += 1
      elif self._count ==1:
        self._data['tomorrow'] = {}
        self._data['tomorrow']['text'] = attrs['text']
        self._data['tomorrow']['low'] = attrs['low']
        self._data['tomorrow']['high'] = attrs['high']
        self._count += 1
        
  def end_element(self,name):
    pass
  def char_data(self,text):
    pass
def parse_weather(xml):
  p = ParserCreate()
  a = A()
  p.StartElementHandler = a.start_element
  p.EndElementHandler = a.end_element
  p.CharacterDataHandler = a.char_data
  p.Parse(xml)
  return a.get_data()

weather = parse_weather(data)
assert weather['city'] == 'Beijing', weather['city']   #这些assert语句是一个断点,如果城市不是北京就报错
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))

'''
输出:
weather: {'country': 'China', 'today': {'text': 'Partly Cloudy', 'low': '20', 'high': '33'}, 'tomorrow': {'text': 'Sunny', 'low': '21', 'high': '34'}, 'city': 'Beijing'}
'''
从这一段xml代码里面我们发现所需要的内容全部都是在标签头里面,所以只需要在start_element方法里面协商合适的判断条件去获得所需要的内容即可。


       


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值