【转】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(',') 复制字符 ...
随机推荐
- zoj1871steps 数学 水
zoj1871 题目大意 ...
- 【Vue】浅谈Vue(一):从模板语法数据绑定、指令到计算属性
写在前面 今年前端届比较有意思,从大漠穷秋发表文章比较angular和vue,继而致歉vue作者.社区,从谷歌辞去Angular Developer PM in China一职并且呼吁大家停止各种无谓 ...
- 【转载】jQuery动画中的queue()函数
原文链接:http://www.cnblogs.com/hh54188/archive/2011/04/09/1996469.html 原文摘要:当你使用一系列的动画效果(如hide,show),这些 ...
- WAMPServer配置修改及问题汇总
备忘录 软件版本wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-64b -------------------------------------- ...
- 系统讲解CSS,前端开发最神奇的技术,新手的你一定不能错过
前面小编带领大家重温了前端开发中最基本的HTML语言.如果你已经掌握了这门语言,那么恭喜你,可以去深入了解CSS技术了.CSS技术最主要的功能就是弥补HTML标记对在页面中显示外观的不足,对这些标记对 ...
- Noip2016愤怒的小鸟(状压DP)
题目描述 题意大概就是坐标系上第一象限上有N只猪,每次可以构造一条经过原点且开口向下的抛物线,抛物线可能会经过某一或某些猪,求使所有猪被至少经过一次的抛物线最少数量. 原题中还有一个特殊指令M,对于正 ...
- GTK主题黑边问题
Linux就是这样,上游一出点什么奇怪的变动,下游程序就要受影响..最近滚了一下后,不知道mesa还是xf86-intel-video哪个玩了什么新花样,所有gtk应用[主要是gnome组件]全部自带 ...
- Windows下Mysql5.7开启binlog步骤及注意事项
1.查看是否开启了binlog:show binary logs; 默认情况下是不开启的. 2.开启binlog:修改mysql的配置文件my.ini.添加如下配置: 该文件默认不允许修改,需要右键“ ...
- phalcon——访问控制列表ACL
一个完整的使用实例(将acl封装成一个插件使用): use Phalcon\Acl; use Phalcon\Acl\Role; use Phalcon\Acl\Resource; use Phalc ...
- CentOS设置系统时间、硬件时间、以及定时校对时间
CentOS设置系统时间和时区 一.设置时区 方法一:使用setup工具 setup 选择Timezone configuration 选择Asia/Shanghai 空格键勾选上System clo ...