使用ElementTree解析xml(python3.4)

1、movies.xml

<collection shelf="New Arrivals">
    <movie title="Enemy Behind">
       <type>War, Thriller</type>
       <format>DVD</format>
       <year>2003</year>
       <rating>PG</rating>
       <stars>10</stars>
       <description>Talk about a US-Japan war</description>
    </movie>
    <movie title="Transformers">
       <type>Anime, Science Fiction</type>
       <format>DVD</format>
       <year>1989</year>
       <rating>R</rating>
       <stars>8</stars>
       <description>A schientific fiction</description>
    </movie>
</collection>

 

2、python代码

import xml.etree.ElementTree as ET
tree = ET.parse("e:/movies.xml")
#root = ET.fromstring(country_data_as_string)  #导入字符串
root = tree.getroot() #前三句导入数据并获取根元素 print (root.tag) #取标签名 print (root.attrib) #取属性(字典形式) for movie in root: print ('*'*30) print ("title:", movie.attrib['title']) #取属性值 print ("type:", movie[0].text) #取子节点的内容(元素值)

 

 

3、一些方法

Element.findAll():查找当前element的孩子的属于某个tag的element;

Element.find():查找属于某个tag的第一个element;

Element.text:访问Element的文本内容;

Element.get():访问Element的属性; (当属性>1的时候很有用)

Element.iter():迭代遍历子节点。

for movie in root.iter('movie'):
    print (movie.attrib)

#感觉和下面效果一样,不知道iter()有何妙用
for movie in root:
    print (movie.attrib)

 

 

 

http://www.cnblogs.com/CheeseZH/p/4026686.html

https://docs.python.org/3.4/library/xml.etree.elementtree.html

 

转载于:https://www.cnblogs.com/stellar/p/5984089.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值