python解析xml文件—ElementTree

解析xml文件,python有xml模块,其中有两种方式:①自带的ElementTree,②C语言版的cElementTree。推荐使用C语言版的,这个效率更高,更快。
以下是相关实现方法:


被解析的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>
   <movie title="Trigun">
   <type>Anime, Action</type>
   <format>DVD</format>
   <episodes>4</episodes>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
   <type>Comedy</type>
   <format>VHS</format>
   <rating>PG</rating>
   <stars>2</stars>
   <description>Viewable boredom</description>
</movie>
</collection>

代码实现:

# 解析xml文件
import xml.etree.cElementTree as ET #重点掌握这种方法来解析xml文件 ElementTree 方便、高效

#加载xml文件
xml_tree=ET.parse("file_set/test.xml")

#获得xml文件的根节点
root=xml_tree.getroot()

#获得根目录的标签信息
print("根目录为:{0},其属性值为:{1}".format(root.tag,root.get("shelf"))) #tag获得标签名,get方法获得属性
#所有的字标签(子节点)都是放在根目录里 因此遍历根节点得到子节点
for child_nodes in root.findall("movie"): #先找到子节点movie 再找其子节点 一层一层找
    print("    标签名为:"+child_nodes.tag+","+"属性值为:"+child_nodes.get("title"))
    for child_node in child_nodes:
        print("        标签名为:"+child_node.tag+","+"节点值为:"+child_node.text) #text 获得标签值
# 获得这些信息后就可以把这些信息写入 某个格式的文档中了,大家可以思考下 

处理结果:

根目录为:collection,其属性值为:New Arrivals
    标签名为:movie,属性值为:Enemy Behind
        标签名为:type,节点值为:War, Thriller
        标签名为:format,节点值为:DVD
        标签名为:year,节点值为:2003
        标签名为:rating,节点值为:PG
        标签名为:stars,节点值为:10
        标签名为:description,节点值为:Talk about a US-Japan war
    标签名为:movie,属性值为:Transformers
        标签名为:type,节点值为:Anime, Science Fiction
        标签名为:format,节点值为:DVD
        标签名为:year,节点值为:1989
        标签名为:rating,节点值为:R
        标签名为:stars,节点值为:8
        标签名为:description,节点值为:A schientific fiction
    标签名为:movie,属性值为:Trigun
        标签名为:type,节点值为:Anime, Action
        标签名为:format,节点值为:DVD
        标签名为:episodes,节点值为:4
        标签名为:rating,节点值为:PG
        标签名为:stars,节点值为:10
        标签名为:description,节点值为:Vash the Stampede!
    标签名为:movie,属性值为:Ishtar
        标签名为:type,节点值为:Comedy
        标签名为:format,节点值为:VHS
        标签名为:rating,节点值为:PG
        标签名为:stars,节点值为:2
        标签名为:description,节点值为:Viewable boredom
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值