python 解析xml 文件: Element Tree 方式
环境
python:3.4.4
准备xml文件
首先新建一个xml文件,countries.xml。内容是在python官网上看到的。
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<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>
准备python文件
新建一个test_ET.py,用来解析xml文件。
#!/usr/bin/python
# -*- coding=utf-8 -*- import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element tree = ET.parse('countries.xml') nodes = tree.findall("country") for node in nodes:
#search node & attribute & text
print ("*****Country*****")
if node.attrib["name"]:
print ("Name:",node.attrib["name"]) rank=node.find("rank")
print ("Rank:",rank.text) year=node.find("year")
print ("Year:",year.text) gdppc=node.find("gdppc")
print ("Gdppc:",gdppc.text) neighbors=node.findall("neighbor")
for neighbor in neighbors:
print ("Neighbor:",neighbor.attrib["name"]) #add node
rank=node.find("rank")
element=Element("rank_next", {"name":"Rank","create":""})
element.text=""
rank.append(element) #delete node
year=node.find("year")
node.remove(year) #add node attribute
node.set("force","NewForce")
#update node attribute
node.set("name","NewNode")
#delete node attribute
neighbors=node.findall("neighbor")
for neighbor in neighbors:
del neighbor.attrib["direction"] #add node text
neighbors=node.findall("neighbor")
for neighbor in neighbors:
neighbor.text = "Hello,Neighbor"
#update node text
gdppc=node.find("gdppc")
gdppc.text = ""
#delete node text
rank=node.find("rank")
rank.text = "" tree.write("./out.xml", encoding="utf-8",xml_declaration=True)
执行结果
控制台:
>python test_ET.py
*****Country*****
Name: Liechtenstein
Rank: 1
Year: 2008
Gdppc: 141100
Neighbor: Austria
Neighbor: Switzerland
*****Country*****
Name: Singapore
Rank: 4
Year: 2011
Gdppc: 59900
Neighbor: Malaysia
*****Country*****
Name: Panama
Rank: 68
Year: 2011
Gdppc: 13600
Neighbor: Costa Rica
Neighbor: Colombia
out.xml文件:
<?xml version='1.0' encoding='utf-8'?>
<data>
<country force="NewForce" name="NewNode">
<rank><rank_next create="20151231" name="Rank">5</rank_next></rank>
<gdppc>11111</gdppc>
<neighbor name="Austria">Hello,Neighbor</neighbor>
<neighbor name="Switzerland">Hello,Neighbor</neighbor>
</country>
<country force="NewForce" name="NewNode">
<rank><rank_next create="20151231" name="Rank">5</rank_next></rank>
<gdppc>11111</gdppc>
<neighbor name="Malaysia">Hello,Neighbor</neighbor>
</country>
<country force="NewForce" name="NewNode">
<rank><rank_next create="20151231" name="Rank">5</rank_next></rank>
<gdppc>11111</gdppc>
<neighbor name="Costa Rica">Hello,Neighbor</neighbor>
<neighbor name="Colombia">Hello,Neighbor</neighbor>
</country>
</data>
备注
具有方便友好的API。代码可用性好,速度快,消耗内存少。
最适合用来处理XML文档。
参考:https://docs.python.org/2/library/xml.etree.elementtree.html
tree = ET.parse('countries.xml')
解析countries.xml并返回一个树。
tree.write("./out2.xml", encoding="utf-8",xml_declaration=True)
将元素树写入到文档,采用 “utf-8”编码,具有xml声明。
write(file, encoding="us-ascii", xml_declaration=None, default_namespace=None, method="xml")
Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding [1] is the output encoding (default is US-ASCII). xml_declaration controls if an XML declaration should be added to the file. Use False for never, True for always, None for only if not US-ASCII or UTF-8 (default is None). default_namespace sets the default XML namespace (for “xmlns”). method is either "xml", "html" or "text" (default is "xml"). Returns an encoded string.
python 解析xml 文件: Element Tree 方式的更多相关文章
- Python 解析 XML 文件生成 HTML
XML文件result.xml,内容如下: <ccm> <metric> <complexity>1</complexity> <unit> ...
- 横向对比分析Python解析XML的四种方式
横向对比分析Python解析XML的四种方式 在最初学习PYTHON的时候,只知道有DOM和SAX两种解析方法,但是其效率都不够理想,由于需要处理的文件数量太大,这两种方式耗时太高无法接受. 在网络搜 ...
- python 解析xml 文件: DOM 方式
环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...
- python 解析xml 文件: SAX方式
环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...
- [转载] python 解析xml 文件: SAX方式
环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...
- 【TensorFlow】Python解析xml文件
最近在项目中使用TensorFlow训练目标检测模型,在制作自己的数据集时使用了labelimg软件对图片进行标注,产生了VOC格式的数据,但标注生成的xml文件标签值难免会产生个别错误造成程序无法跑 ...
- python 解析 XML文件
如下使用xml.etree.ElementTree模块来解析XML文件.ElementTree模块中提供了两个类用来完成这个目的: ElementTree表示整个XML文件(一个树形结构) Eleme ...
- 遍历文件 创建XML对象 方法 python解析XML文件 提取坐标计存入文件
XML文件??? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. 里面的标签都是可以随心所欲的按照他的命名规则来定义的,文件名为roi.xm ...
- Python解析xml文件遇到的编码解析的问题
使用python对xml文件进行解析的时候,假设xml文件的头文件是utf-8格式的编码,那么解析是ok的,但假设是其它格式将会出现例如以下异常: xml.parsers.expat.ExpatErr ...
随机推荐
- 【转】 OC基础数据类型-NSSet
原文 : http://www.cnblogs.com/GISerYang/p/3340937.html 1.集合:集合(NSSet)和数组(NSArray)有相似之处,都是存储不同的对象的地址:不过 ...
- 把cygwin加入右键菜单
第一步:修改windows注册表 1·开始->运行(或者win键+R),输入REGEDIT,回车,打开注册表编辑器: 2·找到HKEY_CLASSES_ROOT\Directory\Backgr ...
- LA 6476 Outpost Navigation (DFS+剪枝)
题目链接 Solution DFS+剪枝 对于一个走过点k,如果有必要再走一次,那么一定是走过k后在k点的最大弹药数增加了.否则一定没有必要再走. 记录经过每个点的最大弹药数,对dfs进行剪枝. #i ...
- splice 操作符
几乎所有的数组操作都可用 splice 实现. 除了第一个参数,数组,为必须,其余的参数都不是必须的. splice ARRAY, OFFSET, LENGTH, LIST OFFSET 和 LENG ...
- Html5新增加的属性
用2中方法给单复选框增加新的特性,使直接点击文字就可以被选中 1.将选项放入label标签内添加for属性,并在input标签内添加id,两者值相同. 2.将input标签放到label标签内,注意l ...
- Linux常用命令大全(2)
系统信息arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS / ...
- php基础知识【函数】(5)正则preg
一.匹配次数 (1) * 匹配前面的子表达式零次或多次 (2) + 匹配前面的子表达式一次或多次,+ 等价于 {1,} (3) ? 匹配前面的子表达式零次或一次,? 等价于 {0,1} (4){n} ...
- python str + int
TypeError: cannot concatenate 'str' and 'int' objects 1. print 'Is your secret number " + str(p ...
- git extrad_addons 部署说明
注册一个git账号 : 网址: https://github.com/ 1:安装git sudo apt-get install git 2: b把urc扩展占模块pull下来 cd ...
- 一个简单的多线程Python爬虫(一)
一个简单的多线程Python爬虫 最近想要抓取拉勾网的数据,最开始是使用Scrapy的,但是遇到了下面两个问题: 前端页面是用JS模板引擎生成的 接口主要是用POST提交参数的 目前不会处理使用JS模 ...