原文地址: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. javascript bom 编程

     javascript bom  编程 BOM: 浏览器对象模型 DOM Window  :窗口Window Document 属性:     status :状态栏     self:自己    ...

  2. 提取多层嵌套Json数据

    在.net 2.0中提取这样的json {"name":"lily","age":23,"addr":{"ci ...

  3. 文件上传之--内存溢出(System.OutOfMemoryException)

    两周前就想把这点经验记录下来了,由于拖延症上身,直到刚才突然想起这件未完成的任务,今天是1024,在这个特别的日子里,祝所有程序猿兄弟姐妹们节日快乐! 上传功能一直很正常,直到上传了个500多兆的文件 ...

  4. 深入浅出 Spring

    前言:笔记中提供了大量的代码示例,需要说明的是,大部分代码示例都是以图片的形式展示的,所有的图片都是来自本人所敲代码的截图,不足之处,请大家指正~ 第一部分:环境搭建及 IOC 容器 一.Spring ...

  5. interface接口

    当一个抽象类中的方法都是抽象的时候,这时可以将该抽象类用另一种形式定义和表示,就是接口 interface. 定义接口使用的关键字不是class,是interface.接口中常见的成员: 这些成员都有 ...

  6. iOS正确使用const,static,extern

    static 修饰局部变量 让局部变量只初始化一次 局部变量在程序中只有一份内存 并不会改变局部变量的作用域,仅仅是改变了局部变量的生命周期(只到程序结束,这个局部变量才会销毁) 修饰全局变量 全局变 ...

  7. ZendStudio-12.5.0-win32.win32.x86_64.msi官方版本及破解工具

    网上的工具试了好多,最后下载的这个工具成功了,之前的N个工具都失败了 亲自试用,表示有效!!! ZendStudio-12.5.0-win32.win32.x86_64.msi官方版本下载地址:  百 ...

  8. javascrip实现:若选中TreeView的父节点checkbox,则其子节点全部选中;子节点全部没选中,则父节点也会没选中。

    <script type="text/javascript"> function public_GetParentByTagName(element, tagName) ...

  9. dubbo 笔记-XML配置文件简介

    <dubbo:service/> 服务配置,用于暴露一个服务,定义服务的元信息,一个服务可以用多个协议暴露,一个服务也可以注册到多个注册中心. eg.<dubbo:service r ...

  10. 100. Same Tree(leetcode)

    Given two binary trees, write a function to check if they are equal or not. Two binary trees are con ...