使用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