环境

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 方式的更多相关文章

  1. Python 解析 XML 文件生成 HTML

    XML文件result.xml,内容如下: <ccm> <metric> <complexity>1</complexity> <unit> ...

  2. 横向对比分析Python解析XML的四种方式

    横向对比分析Python解析XML的四种方式 在最初学习PYTHON的时候,只知道有DOM和SAX两种解析方法,但是其效率都不够理想,由于需要处理的文件数量太大,这两种方式耗时太高无法接受. 在网络搜 ...

  3. python 解析xml 文件: DOM 方式

    环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...

  4. python 解析xml 文件: SAX方式

    环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...

  5. [转载] python 解析xml 文件: SAX方式

    环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...

  6. 【TensorFlow】Python解析xml文件

    最近在项目中使用TensorFlow训练目标检测模型,在制作自己的数据集时使用了labelimg软件对图片进行标注,产生了VOC格式的数据,但标注生成的xml文件标签值难免会产生个别错误造成程序无法跑 ...

  7. python 解析 XML文件

    如下使用xml.etree.ElementTree模块来解析XML文件.ElementTree模块中提供了两个类用来完成这个目的: ElementTree表示整个XML文件(一个树形结构) Eleme ...

  8. 遍历文件 创建XML对象 方法 python解析XML文件 提取坐标计存入文件

    XML文件??? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. 里面的标签都是可以随心所欲的按照他的命名规则来定义的,文件名为roi.xm ...

  9. Python解析xml文件遇到的编码解析的问题

    使用python对xml文件进行解析的时候,假设xml文件的头文件是utf-8格式的编码,那么解析是ok的,但假设是其它格式将会出现例如以下异常: xml.parsers.expat.ExpatErr ...

随机推荐

  1. Android App优化建议(转载)

    假如要Google Play上做一个最失败的案例,那最好的秘诀就是界面奇慢无比.耗电.耗内存.接下来就会得到用户的消极评论,最后名声也就臭了.即使你的应用设计精良.创意无限也没用. 耗电或者内存占用等 ...

  2. Windows的计划任务

    阅读目录 一:什么是Windows的计划任务? 二:如何设置计划任务 三:高级设置计划任务 一:什么是Windows的计划任务? 在日常的工作中,我们都有一些固定的或临时性的工作,而每次在爱机前一坐, ...

  3. SQLite 入门教程(二)创建、修改、删除表

    一.数据库定义语言 DDL 在关系型数据库中,数据库中的表 Table.视图 View.索引 Index.关系 Relationship 和触发器 Trigger 等等,构成了数据库的架构 Schem ...

  4. 分享最近和同事处理的 解析XML的相关问题

    CREATE OR REPLACE PROCEDURE BATCHINSERTSK_DEVICE_RECORD1(      xmlstr  IN clob,          v_commits o ...

  5. IOS-textField

    //初始化textfield并设置位置及大小 UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, ...

  6. iOS 中如何监测某段代码运行的时间

    在iOS里面有时间涉及到网络请求,有时间涉及到数据库的查询,我们需要计算该段代码的效率, 以及执行时间方面的问题,为此,可以使用下面方法: double a = CFAbsoluteTimeGetCu ...

  7. js对象的复制,传递,新增,删除和比较

    当我们把一个某个对象拷贝或者传递给某个函数时,往往传递的是该对象的引用. 因此我们在引用上做的任何改动,都将会影响到它所引用的原对象.  复制,拷贝  var o = { add: 'Changdao ...

  8. for语句嵌套使用 实现9*9乘法表

         这个实例主要考察对for循环语句的使用,出现递增规律的乘法表. 开发环境      开发工具:Microsoft Visual Studio2010 旗舰版 具体步骤      先是制作一个 ...

  9. 小心DriveInfo类IsReady属性的较大延迟问题

    当某些驱动器调用IsReady属性来判断是否准备好时,会有性能问题,会非常慢,特别是网络驱动器断开的时候,这个属性会有30秒左右的延迟,这对程序执行是非常大的开销,请慎重调用

  10. 学习笔记--【转】Parameter与Attribute的区别&servletContext与ServletConfig区别

    原文链接http://blog.csdn.net/saygoodbyetoyou/article/details/9006001   Parameter与Attribute的区别   request. ...