【转】python XML 操作总结(创建、保存和删除,支持utf-8和gb2312)
原文地址:http://hi.baidu.com/tbjmnvbagkfgike/item/6743ab10af43bb24f6625cc5
最近写程序需要用到xml操作,看了看python.org上面的几个xml类库,还是一头雾水,感觉太学术化了,都那么吝惜写几个例子。所以自己整理了一下,算是个小总结,和大家分享一下吧。
对于简单的操作xml文件来说,xml.dom.minidom足以,可以写可以读的。
先给出示例程序,然后简单注释一下
1.示例程序:
-----------------------------------------------------------------------------------------------------------------
# Author: Nonove. nonove[at]msn[dot]com
# XML simple operation Examples and functions
# encoding = gbk from xml.dom import minidom
import codecs def write_xml_file(path, xmlDom, option = {'encoding':'utf-8'}):
""" Generate xml file with writer
params:
string path xml file path
Dom xmlDom xml dom
dictionary option writer option {'indent': '', 'addindent':' ', 'newl':'\n', 'encoding':'utf-8'}
returns:
bool success return True else False
"""
defaultOption = {'indent': '', 'addindent':' ', 'newl':'\n', 'encoding':'utf-8'}
for k, v in defaultOption.iteritems():
if k not in option:
option[k] = v try:
f=file(path, 'wb')
writer = codecs.lookup(option['encoding'])[3](f)
xmlDom.writexml(writer, encoding = option['encoding'], indent = option['indent'], \
addindent = option['addindent'], newl = option['newl'])
writer.close()
return True
except:
print('Write xml file failed.... file:{0}'.format(path))
return False if __name__ == "__main__":
# Create a xml dom
xmlDom = minidom.Document()
nonove = xmlDom.createElement('nonove')
xmlDom.appendChild(nonove) # Generate a xml dom
# Create child node, textnode, set attribute, appendChild
for i in range(3):
node = xmlDom.createElement('node')
node.setAttribute('id', str(i))
node.setAttribute('status', 'alive')
textNode = xmlDom.createTextNode('node value ' + str(i))
node.appendChild(textNode)
nonove.appendChild(node) # Print xml dom
# Print simple xml
## print(xmlDom.toxml())
# Print pretty xml
print('\n' + xmlDom.toprettyxml(indent=' ')) # Save xml file with encoding utf-8
option = {'indent': '', 'addindent':'', 'newl':'', 'encoding':'utf-8'}
write_xml_file('nonove.xml', xmlDom, option) # Load xml dom from file
xmlDom = minidom.parse('nonove.xml')
# Get nonove node
nonove = xmlDom.getElementsByTagName('nonove')[0]
# Get node list
nodes = xmlDom.getElementsByTagName('node')
for node in nodes:
# Get node attribute id
nodeid = node.getAttribute('id')
# Print node id and textnode value
print('Node id: {0} textnode value: {1}'.format(nodeid, node.firstChild.nodeValue)) for node in nodes:
# Set attribute or remove attribute
node.setAttribute('author', 'nonove')
node.removeAttribute('status') # Remove node 1
nonove.removeChild(nodes[1]) print('\n' + xmlDom.toprettyxml(indent=' '))
------------------------------------------------------------------------------------------------------------------
2.注释:
#读取xml方式有两种 从文件 和 从字符串
xmlDom =
minidom.parse('nonove.xml')
xmlDom = minidom.parseString(xmlstring)
#创建xml dom
主要是用到了minidom.Document()
xmlDom =
minidom.Document()
#创建/删除节点
node =
xmlDom.createElement('node')
root.removeChild(node)
#创建Text Node,获取 node value
textnode =
xmlDom.createTextNode('set value here')
value = textnode.nodeValue
#添加/删除node属性
node.setAttribute('author',
'nonove')
node.removeAttribute('author')
#保存xml文件
用到了codecs类库和writexml()函数,例子里面我写了个函数,把略显复杂的操作封装了一下,以后可以方便重用。
write_xml_file(path, xmlDom,
option)
path:xml文件保存地址
xmlDom: xml document
option:
是dictionary类型变量,包括缩进和编码等,这个可以方便的把xml文件按utf-8或者gb2312保存,方便。
3.备注:
关于CharacterData的解析不出来的问题解决办法:<![CDATA[]]>标签和两面的节点不能够有间隔字符,否则就解析为空。
<nodename><![CDATA[my data data]]></nodename>
就先总结了这么多,有什么不对的地方或者更好的方法请赐教啊……
转载请注明原文地址啊,辛辛苦苦的总结出来的,别人的劳动成果不容易。
【转】python XML 操作总结(创建、保存和删除,支持utf-8和gb2312)的更多相关文章
- 转 Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
转自: http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html 黄聪:Python 字符串操作(string替换.删除.截取. ...
- Python XML操作
XML(可扩展性标记语言)是一种非常常用的文件类型,主要用于存储和传输数据.在编程中,对XML的操作也非常常见. 本文根据python库文档中的xml.etree.ElementTree类来进行介绍X ...
- PHP下进行XML操作(创建、读取)
PHP下可以使用DOMDocument类对XML或者HTML文件进行读写操作 更为简单的方法使用simpleXML类操作XML DOM节点分为 元素节点 属性节点 值节点 注释节点 根节点(docum ...
- mac 中git操作账号的保存与删除
保存: 在mac中自动保存git的用户名和密码很简单,只需要在终端命令行中输入下面的命令就是: git config --global credential.helper osxkeychain 然后 ...
- mac 中 git 操作账号的保存与删除
mac 系统中,运行命令:git config -l,输出中看到credential.helper=osxkeychain时,说明 git 密码保存在 Keychain 中. 右上角搜索框内搜索 gi ...
- SQL-表的操作(创建表,删除表,更改列,插入新行,更改行的值,删除表中数据)
一,操作表及列 1.创建表: CREATE TABLE test (ID int PRIMARY KEY IDENTITY,Name varchar(20) ) 2.删除表 DROP TABLE t ...
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
去空格及特殊符号 s.strip().lstrip().rstrip(',') 复制字符串 #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sStr2 = sStr1 sS ...
- 黄聪:Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
去空格及特殊符号 s.strip().lstrip().rstrip(',') 复制字符串 #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sStr2 = sStr1 sS ...
- Python 字符串操作
Python 字符串操作(string替换.删除.截取.复制.连接.比较.查找.包含.大小写转换.分割等) 去空格及特殊符号 s.strip() .lstrip() .rstrip(',') 复制字符 ...
随机推荐
- How to Add Columns to a DataGrid through Binding and Map Its Cell Values
How to Add Columns to a DataGrid through Binding and Map Its Cell Values Lance Contreras, 7 Nov 2013 ...
- MVVM框架解析(一)
花了一点时间看了一下微软开源MVVM代码,受义很多! 从代码整体上看,代码分为四大类, 从图中看不能明白我要表达的意思.显而意见!MainApplicationWindow.xaml是应用程序主窗口( ...
- cocos2dx - 节点管理
接上一节内容:cocos2dx - v2.3.3编辑器骨骼动画 本节主要Cocos2dx中节点的管理及应用 一般用法 用过Cocos2dx应该都有用过addChild,removeChild方法.或者 ...
- nginx URL重写
html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...
- btsync 分享资源
Btsync是一款跨平台软件,可以在不同的设备之间共享文件. Btsync类似于BT下载,用户对用户(多用户)之间的传送. 文档的分享者可以将资源放到文件夹下,生成共享Key,分享给接受者,接受者只需 ...
- ROS Indigo在ubuntu1404上的安装方法
安装配置方法参照 http://wiki.ros.org/indigo/Installation/Ubuntu 以下操作需要保证虚拟机能够正常连接网络. 1.更换源镜像: 将源设置为国内源,我选择的 ...
- Noip2016组合数(数论)
题目描述 组合数表示的是从n个物品中选出m个物品的方案数.举个例子,从(1,2,3) 三个物品中选择两个物品可以有(1,2),(1,3),(2,3)这三种选择方法.根据组合数的定 义,我们可以给出计算 ...
- Spring 笔记总结
1.Spring框架的核心是提供一个容器(BeanFactory 或 ApplicationContext),提供以下功能: 1)创建和销毁组件对象,类似"工厂类" 2)采用不同的 ...
- Spring事务的传播行为和隔离级别
事物注解方式: @Transactional [一]传播行为: 使用方法:@Transactional(propagation=Propagation.REQUIRED) Require:支持当前事务 ...
- MySQL常用配置参数
基本配置: datadir:指定mysql的数据目录位置,用于存放mysql数据库文件.日志文件等. 配置示例:datadir=D:/wamp/mysqldata/Data default-chara ...