当前位置: 首页 > news >正文

Python入门:常用模块—xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单

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

<data>

    <country name="Liechtenstein">

        <rank updated="yes">2</rank>

        <year updated="yes">2010</year>

        <gdppc>141100</gdppc>

        <neighbor direction="E" name="Austria" />

        <neighbor direction="W" name="Switzerland" />

    </country>

    <country name="Singapore">

        <rank updated="yes">5</rank>

        <year updated="yes">2013</year>

        <gdppc>59900</gdppc>

        <neighbor direction="N" name="Malaysia" />

    </country>

    <country name="Panama">

        <rank updated="yes">69</rank>

        <year updated="yes">2013</year>

        <gdppc>13600</gdppc>

        <neighbor direction="W" name="Costa Rica" />

        <neighbor direction="E" name="Colombia" />

    </country>

</data>

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

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)

    for in child:

        print(i.tag, i.text)

# 遍历year节点

for node in root.iter('year'):

    print(node.tag, node.text)

# 修改和删除xml文档内容

# 修改

for node in root.iter('year'):

    new_year = int(node.text) + 1

    node.text = str(new_year)

    node.set('updated''yes')

tree.write("xmltest.xml")

# 删除

for country in root.findall('country'):

    rank = int(country.find('rank').text)

    if rank > 50:

        root.remove(country)

tree.write('output.xml')

自己创建xml文档

new_xml = ET.Element("namelist")

name = ET.SubElement(new_xml, "name", attrib={"enrolled""yes"})

age = ET.SubElement(name, "age", attrib={"checked""no"})

sex = ET.SubElement(name, "sex")

sex.text = '33'

name2 = ET.SubElement(new_xml, "name", attrib={"enrolled""no"})

age = ET.SubElement(name2, "age")

age.text = '19'

et = ET.ElementTree(new_xml)        # 生成文档对象

et.write("test.xml", encoding="utf-8", xml_declaration=True)

ET.dump(new_xml)   # 打印生成的格式

http://www.lryc.cn/news/301815.html

相关文章:

  • 蓝队应急响应工具箱v2024.1​
  • Linux中获取字符串长度与获取子字符串
  • Rust语言之sha-256爆破
  • Rust中的字符串处理及相关方法详解
  • NS安装-CentOS服务器安装Nightscout CGM
  • 利用ChatGPT提升工作效率
  • django admin页面美化
  • Git 操作以及Git 常见问题
  • 如何学习和规划类似ChatGPT这种人工智能(AI)相关技术
  • 4 月 9 日至 4 月 10 日,Hack.Summit() 2024 首聚香江
  • [力扣 Hot100]Day29 删除链表的倒数第 N 个结点
  • 探索设计模式的魅力:掌握命令模式-解锁软件设计的‘遥控器’
  • LNMP搭建discuz论坛
  • 257.【华为OD机试真题】幼儿园篮球游戏(贪心算法-JavaPythonC++JS实现)
  • [计算机网络]深度学习传输层TCP协议
  • 动态头部:统一目标检测头部与注意力
  • 【状态估计】深度传感器与深度估计算法(1/3)
  • ClickHouse从入门到精通(高级)
  • 什么是Docker的容器编排工具,它们之间有何不同?
  • qml之Control类型布局讲解,padding属性和Inset属性细讲
  • 【Jvm】性能调优(拓展)Jprofiler如何监控和解决死锁、内存泄露问题
  • 运行错误(竞赛遇到的问题)
  • nodename nor servname provided, or not known
  • 前端vue金额用逗号分隔
  • vulvhub-----Hacker-KID靶机
  • 遨博I20协作臂关节逆解组Matlab可视化
  • 力扣题目训练(15)
  • PCB差模辐射是如何产生的
  • 车载诊断协议DoIP系列 —— 协议中术语解释和定义
  • 【退役之重学前端】关于在控制台得到undefined的事