Python解析生成XML-ElementTree VS minidom
OS:Windows 7
关键字:Python3.4,XML,ElementTree,minidom
本文介绍用Python解析生成以下XML:
<Persons>
<Person>
<Name>LDL</Name>
<Description Language='English'><![CDATA[cdata text]]></Description>
</Person>
<Person>
<Name>China</Name>
<Description Language='English'><![CDATA[cdata text]]></Description>
</Person>
</Persons>
1.创建一个xml文件名为src.xml,内容如上,放到c:\temp
2.使用ElementTree读取src.xml,并创建一个内容相同的xml名为target-tree.xml。
ElementTreeSample.py如下:
# -*- coding: utf-8 -*-
"""
Sample of xml.etree.ElementTree @author: ldlchina
""" import os
import sys
import logging
import traceback
import xml.etree.ElementTree as ET
import time def copy_node(src_node, target_node):
# Copy attr
for key in src_node.keys():
target_node.set(key, src_node.get(key)) if len(list(src_node)) > 0:
for child in src_node:
target_child = ET.Element(child.tag)
target_node.append(target_child)
copy_node(child, target_child)
else:
target_node.text = src_node.text def read_write_xml(src, target):
tree = ET.parse(src)
root = tree.getroot() target_root = ET.Element(root.tag)
start_time = time.time() * 1000
copy_node(root, target_root)
end_time = time.time() * 1000
print('copy_node:' + str(end_time - start_time)) target_tree = ET.ElementTree(target_root)
target_tree.write(target)
logging.info(target) def main():
try:
current_file = os.path.realpath(__file__) # Configure logger
log_file = current_file.replace('.py', '.log')
logging.basicConfig(filename = log_file, filemode = 'w', level = logging.INFO) # Create console handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO) logger = logging.getLogger('')
logger.addHandler(ch) #src = sys.argv[1]
#target = sys.argv[2] # For debugging
src = 'C:/temp/src.xml'
target = 'C:/temp/target-tree.xml' # Generate results
start_time = time.time() * 1000
read_write_xml(src, target)
end_time = time.time() * 1000
print('read_write_xml:' + str(end_time - start_time))
except:
logging.exception(''.format(traceback.format_exc())) input('Press any key to exit...') main()
3.使用minidom读取src.xml,并创建一个内容相同的xml名为target-dom.xml。
MinidomSample.py如下:
# -*- coding: utf-8 -*-
"""
Sample of xml.dom.minidom @author: ldlchina
""" import os
import sys
import logging
import traceback
import xml.dom.minidom as MD
import time def get_text(n):
nodelist = n.childNodes
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE or node.nodeType == node.CDATA_SECTION_NODE:
rc = rc + node.data
return rc def copy_node(target_doc, src_node, target_node):
if not isinstance(src_node, MD.Document) and src_node.hasAttributes():
for item in src_node.attributes.items():
target_node.setAttribute(item[0], item[1])
for node in src_node.childNodes:
if node.nodeType == node.TEXT_NODE:
target_child = target_doc.createTextNode(node.nodeValue)
target_node.appendChild(target_child)
elif node.nodeType == node.CDATA_SECTION_NODE:
target_child = target_doc.createCDATASection(node.nodeValue)
target_node.appendChild(target_child)
elif node.nodeType == node.ELEMENT_NODE:
target_child = target_doc.createElement(node.nodeName)
target_node.appendChild(target_child)
copy_node(target_doc, node, target_child) def read_write_xml(src, target):
doc = MD.parse(src)
target_doc = MD.Document() start_time = time.time() * 1000
copy_node(target_doc, doc, target_doc)
end_time = time.time() * 1000
print('copy_node: ' + str(end_time - start_time)) # Write to file
f = open(target, 'w')
f.write(target_doc.documentElement.toxml())
f.close()
logging.info(target) def main():
try:
current_file = os.path.realpath(__file__) # Configure logger
log_file = current_file.replace('.py', '.log')
logging.basicConfig(filename = log_file, filemode = 'w', level = logging.INFO) # Create console handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO) logger = logging.getLogger('')
logger.addHandler(ch) #src = sys.argv[1]
#target = sys.argv[2] # For debugging
src = 'C:/temp/src.xml'
target = 'C:/temp/target-dom.xml' # Generate results
start_time = time.time() * 1000
read_write_xml(src, target)
end_time = time.time() * 1000
print('read_write_xml: ' + str(end_time - start_time))
except:
logging.exception(''.format(traceback.format_exc())) input('Press any key to exit...') main()
4.运行ElementTreeSample.py,得到XML如下:
<Persons><Person><Name>LDL</Name><Description Language="English">cdata text</Description></Person><Person><Name>China</Name><Description Language="Chinese">cdata text</Description></Person></Persons>
5.运行MinidomSample.py,得到XML如下:
<Persons>
<Person>
<Name>LDL</Name>
<Description Language="English"><![CDATA[cdata text]]></Description>
</Person>
<Person>
<Name>China</Name>
<Description Language="Chinese"><![CDATA[cdata text]]></Description>
</Person>
</Persons>
ElementTree VS minidom:
1.ElementTree执行速度会比minidom快一些。
2.ElemenTree不能分析XML的转行和缩进。minidom可以。
3.ElemenTree不支持CDATA,minidom可以。
Python解析生成XML-ElementTree VS minidom的更多相关文章
- python 批量生成xml标记文件(连通域坐标分割)
#!/usr/bin/python # -*- coding=utf-8 -*- # author : Manuel # date: 2019-05-15 from xml.etree import ...
- xStream解析生成xml文件学习资料
参考链接: http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html
- Python 解析构建数据大杂烩 -- csv、xml、json、excel
Python 可以通过各种库去解析我们常见的数据.其中 csv 文件以纯文本形式存储表格数据,以某字符作为分隔值,通常为逗号:xml 可拓展标记语言,很像超文本标记语言 Html ,但主要对文档和数据 ...
- python解析robot framework的output.xml,并生成html
一.背景 Jenkins自动构建RF脚本,生成的RF特有HTML报告不能正常打开. 需求:用Python解析测试报告的xml数据,放在普通HTML文件中打开 二.output.xml数据 三.用pyh ...
- 【Python】 xml解析与生成 xml
xml *之前用的时候也没想到..其实用BeautifulSoup就可以解析xml啊..因为html只是xml的一种实现方式吧.但是很蛋疼的一点就是,bs不提供获取对象的方法,其find大多获取的都是 ...
- Python 解析 XML 文件生成 HTML
XML文件result.xml,内容如下: <ccm> <metric> <complexity>1</complexity> <unit> ...
- python 解析与生成xml
xml.etree.ElementTree模块为xml文件的提取和建立提供了简单有效的API.下文中使用ET来代表xml.etree.ElementTree模块. XML是一种内在的分层的数据形式,展 ...
- python xml文件解析 及生成xml文件
#解析一个database的xml文件 """ <databaselist type="database config"> <dat ...
- python XML文件解析:用ElementTree解析XML
Python标准库中,提供了ET的两种实现.一个是纯Python实现的xml.etree.ElementTree,另一个是速度更快的C语言实现xml.etree.cElementTree.请记住始终使 ...
随机推荐
- Mysql性能调优
在MYSQL命令行客户端添加 \G 语句终止符可以让返回的结果集垂直显示. 一.查找运行缓慢的 SQL语句 :show full processlist ; 二.生成一个查询执行计划(Query Ex ...
- java 并发官方教程
http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html Concurrency Computer users t ...
- jquery checkbox的判断和设置方法
jquery的操作复选框偶尔能用到,每次都是百度去查,不得不说现在百度的搜索真的很垃圾,好多特别老的文章都排在前面,想要甄别出有用的东西挺费劲.脑子又记不住这么多东西,好记性不如烂笔头,还是记下来吧 ...
- android之模拟器更新底层
Android源码修改,编译后得到system.img 替换\AndroidSDK\system-images\android-21\android-tv\armeabi-v7a\目录中的system ...
- box-shadow学习笔记
CSS3 box-shadow属性的简单学习笔记 语法格式: box-shadow: h-shadow v-shadow blur spread color inset; 值 描述 h-shadow ...
- 【linux操作命令】crontab
带续写... 版权声明:本文为博主原创文章,未经博主允许不得转载.
- PHP之curl
当我第一次接触curl的时候,看文档,以及网上search各种资料,官方(http://cn2.php.net/manual/en/intro.curl.php)的解释是,这是某大牛写的一个libcu ...
- Floyd-Warshall算法详解(转)
Floyd-Warshall算法,简称Floyd算法,用于求解任意两点间的最短距离,时间复杂度为O(n^3).我们平时所见的Floyd算法的一般形式如下: void Floyd(){ int i,j, ...
- 第一次使用并配置Hibernate
1. 环境配置 1.1 hiberante环境配置 hibernate可实现面向对象的数据存储.hibernate的官网:http://hibernate.org/ 官网上选择hibernate OR ...
- [.Net MVC] Win7下IIS部署
这里简单的分三步实现网站的部署. 一.发布 VS2013中有发布选项,在需要发布的工程项目上(就是设置为启动项目的那个)右键,点“发布”选项: 然后会弹出一个窗口: 选择自定义,随便输入一个名字,然后 ...