解析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