19.7.1 教程
这是一个简短的教程使用xml.etree.ElementTree(简称为et)。目标是展示一些构建模块和模块的基本概念
9.7.1.1. XML tree and elements
XML是一种固有的层次化的数据格式,最自然的方式来表示这是树。为此ET有两个方法——ElementTree代表整个XML文档树,Element表示这个树中的一个节点。与整个文档交互(阅读和写作/文件)通常是在ElementTree水平。与一个XML元素及其子元素是元素级别上完成的。
9.7.1.2
xml文件,保存到本地test.xml

<?xml version="1.0" encoding="utf-8"?> <request> <functionID>subPackageInfo</functionID> <time>2014-02-10 15:10:50</time> <packageList> <packageInfo> <orderId id='9001'>22088317130</orderId> <expressName id='1001'>ems</expressName> <expressTel>01</expressTel> <expressNo>0001</expressNo> <productId>1001173023</productId> <allotQuatity>5</allotQuatity> <outOfStockQuatity>0</outOfStockQuatity> <promotionID></promotionID> </packageInfo> <packageInfo> <orderId id='5551'>22088317130</orderId> <expressName id='10086'>23</expressName> <expressTel>010-55675233</expressTel> <expressNo>0002</expressNo> <productId>1001173123</productId> <allotQuatity>5</allotQuatity> <outOfStockQuatity>0</outOfStockQuatity> <promotionID>-1</promotionID> </packageInfo> <packageInfo> <orderId>22088317130</orderId> <expressName>EMS</expressName> <expressTel>010-55675233</expressTel> <expressNo>0003</expressNo> <productId>1001173223</productId> <allotQuatity>0</allotQuatity> <outOfStockQuatity>5</outOfStockQuatity> <promotionID>-1</promotionID> </packageInfo> </packageList> </request>
解析xml文件
from xml.etree import ElementTree tree=ElementTree.parse('test.xml')
#tree= ET.fromstring(country_data_as_string) #fromstring解释字符串,即country_data_as_string为读取xml的字符串
getroot()返回树结构的根元素
get 获取元素的标签
>>> root=tree.getroot() >>> root.tag 'request'
find和findall,如果参数是元素名称的话只能查找当前节点的下一层节点,用法下面再介绍
list=root.find('packageList') infos=list.findall('packageInfo')
查找packageInfo下面的orderId节点的文本
>>> for i in infos: print i.find('orderId').text 22088317130 22088317130 22088317130
find()
1.root.find('packageList') 只匹配root节点下最上层元素,不匹配嵌入另一个元素的元素类型packageList 2.root.find('packageList/packageInfo')直接找到packageInfo节点 3.a=root.findall('*/packageInfo') >>> for i in a:print i.tag packageInfo packageInfo packageInfo 4.我称为xpath方法 a=root.findall('.//orderId') >>> for i in a:print i.text 22088317130 22088317130 22088317130 >>> a=root.findall('.//orderId[@id="9001"]') >>> a[0].text '22088317130'