Python解析xml文件(一)

本文介绍了一个使用Python中的xml.dom.minidom模块解析XML文件的例子。通过这个实例,读者可以了解到如何读取XML文档、获取文档中的节点元素及其属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解析xml文件:
思路:
一、首先获取需要解析的文档的
二、获取解析的文档中的所有的节点元素
三、根据需要调用相关的API获取相应的信息

Python中的xml.dom.minidom模块是用来处理xml文件的,所以在处理xml文件的时候需要把这个模块引入进来

首先写一个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>

获取标签属性:
# -*- coding: UTF-8 -*-

from xml.dom.minidom import parse
import xml.dom.minidom

# 使用minidom解析器打开 XML 文档
DOMTree = xml.dom.minidom.parse("a.xml")
#获取文件中的节点元素
collection = DOMTree.documentElement
#nodeName节点的名字
print collection.nodeName
#nodeValue是结点的值,只对文本结点有效
print collection.nodeValue
#nodeType是结点的类型
print collection.nodeType
#ELEMENT_NODE节点的类型之一
print collection.ELEMENT_NODE

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值