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 ...
随机推荐
- 利用抽象、多态实现无反射的绿色环保ORM框架
最近一直在忙新公司的基础库建设,对系统架构.开发框架及快速开发平台的设计实施都积累了一定的实践经验. 一般的中小型的软件开发公司,如果按照技术储备来衡量软件项目的技术含量的评定依据是可行的.但如果光是 ...
- WampServer修改端口及菜单Localhost
一.修改Apache端口 1.在界面中选Apache,弹出隐藏菜单选项,打开配置文件httpd.conf: 2.找到 Listen 80: 3.将 80 改成 8080(当然自己也可以设定别的不使用的 ...
- SGU 113.Nearly prime numbers
水一个代码: #include <iostream> using namespace std; int n, a; bool ok; bool prime (int x) { ; i * ...
- 解决IE6不支持position:fixed;的问题
在网页设计中,时常要用到把某个元素始终定位在屏幕上,即使滚动浏览器窗口也不会发生变化. 一般我们会使用position:fixed来进行绝对固定,但IE6并不支持position:fixed属性,所以 ...
- 自定义Excel导出简易组件
1.组件原理 excel的数据存储是以xml格式存储的,所以导出Excel文件可以通过生成XML来实现.当然XML必须符合一定的格式要求. 2.组件实现 (1)新建类库文件“MyExcel” (2)添 ...
- 极光推送 api ios参数问题
这是首个app项目,推送用的是极光推送jpush 由于用官方文档出现接收多条的问题,在网上找到一套封装好的,非常感觉这位开发者 //推送.指定人error_reporting(E_ALL^E_NOTI ...
- js获取当前时间戳与日期比较
如何用javascript获取当前时间戳: 复制代码 代码示例: 方法1: var timestamp = date.parse(new date()); 结果:1280977330000 方法2: ...
- 用PHP添加购物商品
<?php session_start(); header ( "Content-type: text/html; charset=UTF-8" ); //设置文件编码格式 ...
- 解决nginx: [error] open() "/usr/local/nginx/logs/nginx.pid" failed错误
重新启动服务器,访问web服务发现无法浏览,登陆服务器之 后进到nginx使用./nginx -s reload重新读取配置文件,发现报nginx: [error] open() "/usr ...
- C语言陷阱——类型转换
以下例子取自<深入理解计算机系统>. 考虑如下的C语言代码: #include<stdio.h> typedef unsigned char* byte_pointer; vo ...