python_xml处理(一)

本文介绍了一种使用Python的ElementTree模块解析XML结构数据的方法。通过具体示例展示了如何读取XML文件、获取节点信息及属性,并遍历特定标签节点。

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

<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2023</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2026</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2026</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</data>
调用:from xml.etree import ElementTree as ET	
使用: ET.XML() 将str类型转换成<class 'xml.etree.ElementTree.Element'>类型
tag 当前标签节点
iter('这个名字'),所有(这个名字)标签节点
find ("名字")寻找节点中包含的节点,只能找一层节点
arrtrib()标签内的属性
from xml.etree import ElementTree as ET
root = ET.XML(open('fist.xml','r',encoding='utf-8').read())
print(type(root))
#tag 是打印最外层标签节点
print(root.tag)
#迭代对应节点iter('要迭代节点的名字')
for node in root.iter('year'):
    print(node)

#迭代下层节点
for node in root:
    #find 寻找节点中包含的节点,只能找一层节点
    #text打印节点中内容
    print(node.find('rank').text)
    #打印节点对应属性
    print(node.find('neighbor').attrib)
>>>>
<class 'xml.etree.ElementTree.Element'>
data
<Element 'year' at 0x000000845B0752C8>
<Element 'year' at 0x000000845B0754A8>
<Element 'year' at 0x000000845B075638>
2
{'name': 'Austria', 'direction': 'E'}
5
{'name': 'Malaysia', 'direction': 'N'}
69
{'name': 'Costa Rica', 'direction': 'W'}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值