Python3的xml模块及其使用

import xml.etree.ElementTree as ET

tree = ET.parse('xml_test')
root = tree.getroot()  # 获取 根节点
print(root.tag)

# 遍历xml文档
for child in root:
    print(child.tag, child.attrib)  # 获取下一级的标签和属性
    for i in child:
        print('  ', i.tag, i.text)  # 获取再下一级的标签和文本

# 只遍历year 节点
for node in root.iter('year'):  # 在 根节点的子节点中过滤出标签‘year’
    print(node.tag, node.text)  # 打印节点标签和文本

# 修改
for node in root.iter('year'):
    new_year = int(node.text) + 1  # 修改获取到的文本 (先转为int 型)
    node.text = str(new_year)  # 再转为string 型
    node.set("updated", "yes")  # 给指定标签 赋值

tree.write("update.xml")  # 持久化

# 删除node
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)  # remove() 方法

tree.write('delete.xml')

操作文件:xml_test.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>

<!--xml数据-->

 要点:

  • parse('file') 解析文件
  • getroot() 获取根节点
  • 根节点可遍历:for child in root: child.tag,child.attrib 其中child.tag 获取子节点标签,child.attrib 获取子节点属性值
  • 上面的child 也是可遍历对象: for i in child: i.tag , i.text 其中i.tag 获取标签,i.text 获取文本
  • iter() 过滤字段 
  • findall() 匹配字段

# 序列化:内存中变成可存储,可传输的过程称之为序列化

# json 流行,更简单
# xml 过时的机制 在java

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值