使用的XML文件如下:file.xml

<?xml version="1.0"?>
<data name="ming">
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>

导入模块

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/11/30 0030 18:18
# @Author : ming
import xml.etree.ElementTree as ET

读取文件

result = ET.parse("file.xml")  # 打开文件
root = result.getroot() # 获取根节点

打印一下根节点信息

print(root.tag, root.attrib)  # 根节点标签和属性值
#运行结果:data {'name': 'ming'}

打印一下根节点的孩子节点

for i in root:  # 循环根节点的孩子节点
print(i.tag, i.attrib) # 打印孩子节点的标签和属性值
print(i[0].tag, i[0].text) # 打印孙子节点中第一个节点的标签和属性值。多层节点都可以通过下标访问
# 运行结果:
# country {'name': 'Singapore'}
# rank 4
# country {'name': 'Panama'}
# rank 68

findall 直接定位节点

for k in root.findall('country'):  # 直接定位该节点
print(k.tag, k.attrib) # 打印孩子节点的标签和属性值
print(k[1].tag, k[1].text) # 打印孙子节点中第一个节点的标签和属性值。多层节点都可以通过下标访问
#运行结果
# country {'name': 'Singapore'}
# year 2011
# country {'name': 'Panama'}
# year 2011

iter 遍历所有节点

for m in root.iter():  # 遍历所有节点
print(m.tag, m.attrib, m.text) # 打印所有节点的标签、属性、值
data {'name': 'ming'} 

country {'name': 'Singapore'} 

rank {} 4
year {} 2011
gdppc {} 59900
neighbor {'name': 'Malaysia', 'direction': 'N'} None
country {'name': 'Panama'} rank {} 68
year {} 2011
gdppc {} 13600
neighbor {'name': 'Costa Rica', 'direction': 'W'} None
neighbor {'name': 'Colombia', 'direction': 'E'} None

运行结果

iter 遍历特定的节点,不遍历子节点

for p in root.iter("country"):  # 遍历所有country节点自身,不遍历子节点
print(p.tag, p.attrib) # 打印所有country节点的标签、属性
#运行结果
# country {'name': 'Singapore'}
# country {'name': 'Panama'}

find 查找第一个匹配的节点

firstCountry = root.find("country")  # 返回第一个tag为country的element,如没有,返回None
print(firstCountry.attrib) # 第一个country节点的属性值
# 运行结果
# {'name': 'Singapore'}

append 增加一个新的节点

newEle = ET.Element("Newtag")  # 新节点的标签
newEle.attrib = {"name": "NewElement", "age": ""} # 新节点的属性
newEle.text = "This is a new element" # 新节点的值
# a = root.find("country") # 第一个country节点
# a.append(newEle) # 在第一个country中添加
#
# root[0].append(newEle) # 根节点中第一个子节点下添加
root.append(newEle) # 把这个新节点放在哪个节点下,这里的root代表根节点
result.write("file.xml") # 写回原文件
<data name="ming">
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica"/>
<neighbor direction="E" name="Colombia"/>
</country>
<Newtag age="20" name="NewElement">This is a new element</Newtag>
</data>

运行结果

修改节点信息

# 修改节点属性
sub1 = root.find("country")
sub1.set("name", "Chinese") # 修改name=chinese
result.write("file.xml") # 写回原文件 # 修改节点值
sub2 = root.find("country")
sub2.find("year").text = "" #修改year的值为2018
result.write("file.xml") # 写回原文件
<data name="ming">
<country name="Chinese">
<rank>4</rank>
<year>2018</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>

删除节点

sub3 = root.find("country")
root.remove(sub3)
result.write("file.xml") # 写回原文件
<data name="ming">
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica"/>
<neighbor direction="E" name="Colombia"/>
</country>
</data>

运行结果

创建新的XML文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/2 0002 14:44
# @Author : ming import xml.etree.ElementTree as ET # 创建一个新的XML文件,根节点为yangyongming
new_xml = ET.Element("yangyongming") # 孩子节点为name,指点父亲节点为new_xml sttrib属性
new_1 = ET.SubElement(new_xml, "name", attrib={"name": "hello"}) # 孙子节点sex 父亲节点new_1
new_s1 = ET.SubElement(new_1, "sex")
# 孙子节点sex 赋值"man"
new_s1.text = "man"
# 孙子节点 age, 父亲节点new_1
new_s2 = ET.SubElement(new_1, "age")
# 孙子节点age 赋值“18”
new_s2.text = "" # 转换为XML文件,写入文件
et = ET.ElementTree(new_xml)
et.write("file.xml", encoding="utf-8")
<yangyongming>
<name name="hello">
<sex>man</sex>
<age>18</age>
</name>
</yangyongming>

运行结果

python xml.etree.ElementTree模块的更多相关文章

  1. xml.etree.ElementTree模块的封装

    转载:https://www.cnblogs.com/hongten/p/hongten_python_xml_etree_elementtree.html 1 # -*- coding: utf-8 ...

  2. [python 学习] 使用 xml.etree.ElementTree 模块处理 XML

    ---恢复内容开始--- 导入数据(读文件和读字符串) 本地文件 country_data.xml <?xml version="1.0"?> <data> ...

  3. python xml.etree ElementTree解析 编辑 xml

    python有很多种xml解析方式,不过感觉etree的ElementTree 用起来最方便. #coding=utf-8 from xml.etree import ElementTree impo ...

  4. python xml.etree.ElementTree解析xml文件获取节点

    <?xml version = "1.0" encoding = "utf-8"?> <root> <body name=&quo ...

  5. Python 标准库之 xml.etree.ElementTree

    Python 标准库之 xml.etree.ElementTree Python中有多种xml处理API,常用的有xml.dom.*模块.xml.sax.*模块.xml.parser.expat模块和 ...

  6. python 之xml.etree.ElementTree

    Element类型是一种灵活的容器对象,用于在内存中存储结构化数据. [注意]xml.etree.ElementTree模块在应对恶意结构数据时显得并不安全. 每个element对象都具有以下属性: ...

  7. python模块:xml.etree.ElementTree

    """Lightweight XML support for Python. XML is an inherently hierarchical data format, ...

  8. python模块之xml.etree.ElementTree

    xml.etree.ElementTree用于解析和构建XML文件 <?xml version="1.0"?> <data> <country nam ...

  9. python标准库xml.etree.ElementTree的bug

    使用python生成或者解析xml的方法用的最多的可能就数python标准库xml.etree.ElementTree和lxml了,在某些环境下使用xml.etree.ElementTree更方便一些 ...

随机推荐

  1. AT24C02跨页写数据

    AT24C02 EEPROM的写数据分为:字节写数据模式和页写数据模式:字节写就是一个地址一个数据的写,页写是连续写数据,一个地址多个数据的写,但是页写不能自动跨页,如果超出一页长度,超出的数据会覆盖 ...

  2. EEPROM---AT24Cxx应用介绍

    结论:1.读写AT24CXX芯片,根据容量有多种方式:一.容量为AT24C01~AT24C16,首先发送设备地址(8位地址),再发送数据地址(8位地址),再发送或者接受数据. 二.AT24C32/AT ...

  3. 自定义CCNode

    对Touch事件的获取与处理可以使用CCLayer, CCMenuItem等,但是如果我们需要一个虚拟按键或者需要对特定精灵进行拖动等等,我们就需要自定义Touch类. 自定义Touch事件处理类重要 ...

  4. 我是SPI,我让框架更加优雅了!

    文章首发于[陈树义的博客],点击跳转到原文<我是 SPI,我让框架更加优雅了!> 自从上次小黑进入公司的架构组之后,小黑就承担起整个公司底层框架的开发工作.就在刚刚,小黑又接到一个任务:做 ...

  5. LeetCode-765.情侣牵手

    N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手. 计算最少交换座位的次数,以便每对情侣可以并肩坐在一起. 一次交换可选择任意两人,让他们站起来交换座位. 人和座位用 0 到 2N-1 的整 ...

  6. windows 服务实现定时任务调度(Quartz.Net)

    我们通常在一些情况下需要软件具有一个自动执行某些任务的功能,但是又不希望直接启动软件,或者每次都要手动的来启动软件,这时我们可可以考虑到windows服务了. 首先创建一个windows服务项目(详细 ...

  7. [转帖]Application Request Route实现IIS Server Farms集群负载详解

    Application Request Route实现IIS Server Farms集群负载详解  https://www.cnblogs.com/knowledgesea/p/5099893.ht ...

  8. Windows 下面简单的同步文件夹工具

    1. 微软自己的工具 下载地址 https://www.microsoft.com/en-us/download/confirmation.aspx?id=15155 2. 安装过程忽略 3. 配置与 ...

  9. Linux学习之CentOS(二)----远程登录管理工具SecureCRT的使用

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/3 ...

  10. 2013长春网赛1005 hdu 4763 Theme Section(kmp应用)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4763 题意:给出一个字符串,问能不能在该串的前中后部找到相同的子串,输出最长的字串的长度. 分析:km ...