python优秀库 - 使用xmltodict解析xml文档

上次讲到如何使用BeautifulSoup解析XML文档,今天发现另外一个python库xmltodict(https://github.com/martinblech/xmltodict)也很简单。

小例子一枚,因为很简单,不需要太多说明

#!/usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = 'liulixiang'
import xmltodict

doc = xmltodict.parse('''<?xml version="1.0"?>
<VehicleInfo has="测试">
  <FileHeader>
    <ScaleInfo>
      <SN>H00120030101081526</SN>
      <UserName>盛隆钢铁</UserName>
      <SUMWeight>0</SUMWeight>
    </ScaleInfo>
  </FileHeader>
  <FileBody>
    <Node>
      <ID>1</ID>
      <_DateTime>2003-1-1 8:14:25</_DateTime>
      <VehicleType />
      <VehicleCardID />
      <Speed>17.5</Speed>
      <Weight>3.12</Weight>
      <PIC1>_1.bmp</PIC1>
    </Node>
    <Node>
      <ID>2</ID>
      <_DateTime>2003-1-1 8:14:26</_DateTime>
      <VehicleType />
      <VehicleCardID />
      <Speed>15.8</Speed>
      <Weight>4.77</Weight>
      <PIC1>_1.bmp</PIC1>
    </Node>
  </FileBody>
</VehicleInfo>
''', encoding='utf-8')

print(doc['VehicleInfo']["@has"])
for node in doc['VehicleInfo']['FileBody']['Node']:
    print(node['ID'], node['Weight'], node['_DateTime'])

 

posted @ 2014-02-08 10:53  刘理想  阅读(3402)  评论(0编辑  收藏  举报