原文地址: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)的更多相关文章

  1. 转 Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)

    转自: http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html 黄聪:Python 字符串操作(string替换.删除.截取. ...

  2. Python XML操作

    XML(可扩展性标记语言)是一种非常常用的文件类型,主要用于存储和传输数据.在编程中,对XML的操作也非常常见. 本文根据python库文档中的xml.etree.ElementTree类来进行介绍X ...

  3. PHP下进行XML操作(创建、读取)

    PHP下可以使用DOMDocument类对XML或者HTML文件进行读写操作 更为简单的方法使用simpleXML类操作XML DOM节点分为 元素节点 属性节点 值节点 注释节点 根节点(docum ...

  4. mac 中git操作账号的保存与删除

    保存: 在mac中自动保存git的用户名和密码很简单,只需要在终端命令行中输入下面的命令就是: git config --global credential.helper osxkeychain 然后 ...

  5. mac 中 git 操作账号的保存与删除

    mac 系统中,运行命令:git config -l,输出中看到credential.helper=osxkeychain时,说明 git 密码保存在 Keychain 中. 右上角搜索框内搜索 gi ...

  6. SQL-表的操作(创建表,删除表,更改列,插入新行,更改行的值,删除表中数据)

    一,操作表及列 1.创建表: CREATE TABLE test (ID int  PRIMARY KEY IDENTITY,Name varchar(20) ) 2.删除表 DROP TABLE t ...

  7. Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)

    去空格及特殊符号 s.strip().lstrip().rstrip(',') 复制字符串 #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sStr2 = sStr1 sS ...

  8. 黄聪:Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)

    去空格及特殊符号 s.strip().lstrip().rstrip(',') 复制字符串 #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sStr2 = sStr1 sS ...

  9. Python 字符串操作

    Python 字符串操作(string替换.删除.截取.复制.连接.比较.查找.包含.大小写转换.分割等) 去空格及特殊符号 s.strip() .lstrip() .rstrip(',') 复制字符 ...

随机推荐

  1. sqlserver常用sql语句,更改字段,建立唯一键,多个字段去重复等

    --修改字段类型: --alter table 表名 alter column 待修改字段名 待修改字段类型 alter table users alter column userid varchar ...

  2. C#仪器数据文件解析-Word文件(doc、docx)

    不少仪器数据报告输出为Word格式文件,同Excel文件,Word文件doc和docx的存储格式是不同的,相应的解析Word文件的方式也类似,主要有以下方式: 1.通过MS Word应用程序的DCOM ...

  3. 如何抽象一个 Vue 公共组件

    之前一直想写一篇关于抽象 Vue 组件的随笔,无奈一直没想到好的例子.恰巧最近为公司项目做了一个数字键盘的组件,于是就以这个为例聊聊如何抽象 Vue 的组件. 先上 Demo 与 源码.(demo最好 ...

  4. 新博客,新开始-从Chrome浏览器奔溃说起

    新博客,新开始 今天是2015-04-09,昨天新开的博客,今天在这写上一段,算是立个标记,好留以后拿来回溯吧. 不知道是谁跟我说的,坚持写博客是个好习惯,也能帮助自己总结经验,提高技术.也许大概可能 ...

  5. Django项目搭建和配置总结

    安装和创建虚拟环境 参考:linux系统下Python虚拟环境的安装和使用 安装Django包 先进入虚拟环境,在联网下执行: pip install django==1.8.7 1.8.7表示dja ...

  6. EL&&JSTL

    一.JSP技术 1.jsp脚本和注释 jsp脚本: 1)<%java代码%> ----- 内部的java代码翻译到service方法的内部 2)<%=java变量或表达式> - ...

  7. C 指针的几个注意点

    1.静态指针在初始化时必须使用编译时可以确定地址表达式完成赋值,如 static int a; static int* pa = &a;//初始化时必须使用可以确定地址的表达式 int b; ...

  8. (原创)(三)机器学习笔记之Scikit Learn的线性回归模型初探

    一.Scikit Learn中使用estimator三部曲 1. 构造estimator 2. 训练模型:fit 3. 利用模型进行预测:predict 二.模型评价 模型训练好后,度量模型拟合效果的 ...

  9. 深入理解final和static关键字

    深入理解final和static关键字 参考:http://blog.csdn.net/qq1028951741/article/details/53418852 final关键字 final关键字可 ...

  10. cordova封装h5为app,cookie不可用解决方法

    //创建cookie function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdat ...