返回顶部

Python之xml模块

Python之xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但是使用起来更简单。在json还没诞生时,大家选择xml,现在很多传统公司的接口主要还是xml。

xml格式,就是通过<>节点来区别数据结构的。

xml协议在各个语言里都是支持的,在Python中可以用以下模块操作xml

复制代码
print(root.iter('year'))                 #全文搜素
print(root.find('country'))             #在root的子节点找,只找一个
print(root.findall('country'))     #在root子节点找,找所有

#xml格式示例
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

---

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
 
#遍历xml文档
for child in root:
    print('========>',child.tag,child.attrib,child.attrib['name'])
    for i in child:
        print(i.tag,i.attrib,i.text)
 
#只遍历year 节点
for node in root.iter('year'):
    print(node.tag,node.text)
复制代码

 

posted @   九尾cat  阅读(101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-06-15 vsftpd启动报错:vsftpd:500 OOPS: bad bool value in config file for: anonymous_enable
2020-06-15 管理创建分区命令
点击右上角即可分享
微信分享提示