python3.6_读取xml文件

此博客为转载内容,转载自https://www.cnblogs.com/xiuxiu123456/p/10893353.html ,涉及Python相关知识。

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

<?xml version="1.0" encoding="UTF-8"?>
<Class>
    <student>
        <name>zhangsan</name>
        <age>23</age>
        <city>beijing</city>
    </student>
    <student>
        <name>lisi</name>
        <age>21</age>
        <city>shanghai</city>
    </student>
    <student>
        <name>wangwu</name>
        <age>22</age>
        <city>shenzhen</city>
    </student>
    <teacher>
        <name>marry</name>
        <age>53</age>
        <city>changsha</city>
    </teacher>
    <account>
        <login username="student" password="123456"/>
        <login username="teacher" password="654321"/>
    </account>
</Class>
from xml.dom import minidom

dom=minidom.parse('C:\\Users\\Administrator\\Desktop\\python-test\\test7.xml')
root=dom.documentElement
#打印节点信息
print(root.nodeName)  #节点名称
print(root.nodeValue)  #节点值
print(root.nodeType)  #节点类型,如果是元素节点返回1,属性节点返回2

print('=============================')

#读取文本节点的值
names=root.getElementsByTagName('name')
ages=root.getElementsByTagName('age')
citys=root.getElementsByTagName('city')

print(names[0].firstChild.data)
print(ages[0].firstChild.data)
print(citys[0].firstChild.data)

print('=============================')

#获取属性节点的值
logins=root.getElementsByTagName('login')
username=logins[0].getAttribute('username')
print(username)
password=logins[0].getAttribute('password')
print(password)

print('=============================')

#打印xml子节点
tags=root.getElementsByTagName('student')
print(tags[0].nodeName)  #节点名称
print(tags[0].nodeValue)  #节点值
print(tags[0].nodeType)  #节点类型

 

转载于:https://www.cnblogs.com/xiuxiu123456/p/10893353.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值