首页 技术 正文
技术 2022年11月9日
0 收藏 463 点赞 3,842 浏览 1568 个字
xml模块
定义:实现不同语言或程序之间进行数据交换的协议。
格式如下:通过<>节点来区别数据结构
如:<load-on-startup(这个是标签) test="value"(这个是属性)>5(这个是文本)</load-on-startup>
root.tag:打印标签
root.attrib:打印属性
root.text:打印文本
举例:
自定义一个stud.xml文件
首先打印各级信息
import xml.etree.ElementTree as et
tree = et.parse('stud.xml') #文件名
root = tree.getroot() #提取根节点
print(root.tag) #打印根标签
1.#遍历xml文档
for child in root:
print(child.tag,child.attrib,child.text) #打印二级节点标签
for i in child:
print(i.tag,i.attrib,i.text) #打印三级节点标签
2:#查找param-name节点
for node in root.iter('param-name'):
print(node.tag,node.attrib,node.text)
#打印:load-on-startup {} 4
3:# 修改使load-on-startup 值加1
for node in root.iter('load-on-startup'): #遍历
new = int(node.text)+1 #匹配load-on-startup值4加1
node.text = str(new) #将新值5替换源值4
node.set('test','value') #为load-on-startup增加属性(test="value")
tree.write('stud.xml') #将修改保存回xml文件
4: 删除操作
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('out.xml')
4:#创建xml文件
import xml.etree.ElementTree as et
#创建根节点
rootlist = et.Element('tech')
#创建二级节点
tech = et.SubElement(rootlist,'tech_node',attrib={'name':'tech_center'})
#创建三级节点
dev = et.SubElement(tech,'dev_node',attrib={'name':'dev_center'})
#写内容
dev.text = 'java'
dev.text = 'python'
test = et.SubElement(tech,'test_node',attrib={'name':'test_center'})
test.text = 'program'
#创建二级节点
finance = et.SubElement(rootlist,'finance_node',attrib={'name':'finance_center'})
#创建三级节点
account = et.SubElement(finance,'account_node',attrib={'name':'account_center'})
account.text = 'woman'
#生成文档对象
obj = et.ElementTree(rootlist)
# 写文件,xml_declaration就是自动在xml文件头加声明
obj.write('stud3.xml',encoding='utf-8',xml_declaration=True)
#可选的屏幕打印
et.dump(rootlist)
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291