博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python模块之xml
阅读量:6903 次
发布时间:2019-06-27

本文共 1947 字,大约阅读时间需要 6 分钟。

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

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

2
2008
141100
5
2011
59900
69
2011
13600

 

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

import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml")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'):    print(node.tag,node.text)

 

修改和删除xml文档内容

import xml.etree.ElementTree as ETtree = ET.parse("xmltest.xml")root = tree.getroot()#修改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")#删除nodefor country in root.findall('country'):   rank = int(country.find('rank').text)   if rank > 50:     root.remove(country)tree.write('output.xml')

 

自己创建xml文档

import xml.etree.ElementTree as ETnew_xml = ET.Element('namelist')  # rootname = ET.SubElement(new_xml, "name", attrib={
"enrolled": "yes"})age = ET.SubElement(name, "age", attrib={
"checked": "no"})sex = ET.SubElement(name, "sex")sex.text = '33'n = ET.SubElement(name, 'name')n.text = 'Alex li'sex.text = 'Male'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) #打印生成的格式

 

转载于:https://www.cnblogs.com/lshedward/p/10003846.html

你可能感兴趣的文章
[LeetCode] 40. Combination Sum II
查看>>
1065. 单身狗(25)
查看>>
《程序员代码面试指南》第八章 数组和矩阵问题 未排序数组中累加和小于或等于给定值的最长子数组长度...
查看>>
23种设计模式
查看>>
ES6_入门(3)_顶层对象属性
查看>>
使用VNC(ubuntu 与 windows 互连 )
查看>>
Map和Stack的STL方法简介
查看>>
Tasks Queues and Cron Jobs(任务队列和时钟守护作业)
查看>>
BZOJ1070[SCOI2007]修车——最小费用最大流
查看>>
elasticsearch映射 mapping
查看>>
UIView常用的一些方法小记之setNeedsDisplay和setNeedsLayout
查看>>
make常见报错原因分析
查看>>
gitlab的安装和配置
查看>>
[转载] OpenCV2.4.3 CheatSheet学习(二)
查看>>
Code::Blocks(完全取代VC6的开源跨平台编程利器)
查看>>
“异或”运算符
查看>>
OpenJudge/Poj 1004 Financial Management
查看>>
模拟 --- 简单括号匹配
查看>>
面向服务(接口)开发过程中常用的实体类数据复制解决方案
查看>>
easyui树动态加载参考
查看>>