【转】python XML 操作总结(创建、保存和删除,支持utf-8和gb2312)

原文地址:http://hi.baidu.com/tbjmnvbagkfgike/item/6743ab10af43bb24f6625cc5

最近写程序需要用到xml操作,看了看python.org上面的几个xml类库,还是一头雾水,感觉太学术化了,都那么吝惜写几个例子。所以自己整理了一下,算是个小总结,和大家分享一下吧。

对于简单的操作xml文件来说,xml.dom.minidom足以,可以写可以读的。

先给出示例程序,然后简单注释一下

1.示例程序:

-----------------------------------------------------------------------------------------------------------------

 

 1 # Author: Nonove. nonove[at]msn[dot]com
 2 # XML simple operation Examples and functions
 3 # encoding = gbk
 4 
 5 from xml.dom import minidom
 6 import codecs
 7 
 8 
 9 def write_xml_file(path, xmlDom, option = {'encoding':'utf-8'}):
10     """ Generate xml file with writer
11     params:
12     string path xml file path
13     Dom xmlDom xml dom
14     dictionary option writer option {'indent': '', 'addindent':' ', 'newl':'\n', 'encoding':'utf-8'}
15     returns:
16     bool success return True else False
17     """
18     defaultOption = {'indent': '', 'addindent':' ', 'newl':'\n', 'encoding':'utf-8'}
19     for k, v in defaultOption.iteritems():
20         if k not in option:
21             option[k] = v
22 
23     try:
24         f=file(path, 'wb')
25         writer = codecs.lookup(option['encoding'])[3](f)
26         xmlDom.writexml(writer, encoding = option['encoding'], indent = option['indent'], \
27         addindent = option['addindent'], newl = option['newl'])
28         writer.close()
29         return True
30     except:
31         print('Write xml file failed.... file:{0}'.format(path))
32         return False
33 
34 
35 
36 if __name__ == "__main__":
37     # Create a xml dom
38     xmlDom = minidom.Document()
39     nonove = xmlDom.createElement('nonove')
40     xmlDom.appendChild(nonove)
41 
42     # Generate a xml dom
43     # Create child node, textnode, set attribute, appendChild
44     for i in range(3):
45         node = xmlDom.createElement('node')
46         node.setAttribute('id', str(i))
47         node.setAttribute('status', 'alive')
48         textNode = xmlDom.createTextNode('node value ' + str(i))
49         node.appendChild(textNode)
50         nonove.appendChild(node)
51 
52     # Print xml dom
53     # Print simple xml
54     ## print(xmlDom.toxml())
55     # Print pretty xml
56     print('\n' + xmlDom.toprettyxml(indent=' '))
57 
58     # Save xml file with encoding utf-8
59     option = {'indent': '', 'addindent':'', 'newl':'', 'encoding':'utf-8'}
60     write_xml_file('nonove.xml', xmlDom, option)
61 
62     # Load xml dom from file
63     xmlDom = minidom.parse('nonove.xml')
64     # Get nonove node
65     nonove = xmlDom.getElementsByTagName('nonove')[0]
66     # Get node list
67     nodes = xmlDom.getElementsByTagName('node')
68     for node in nodes:
69         # Get node attribute id
70         nodeid = node.getAttribute('id')
71         # Print node id and textnode value
72         print('Node id: {0} textnode value: {1}'.format(nodeid, node.firstChild.nodeValue))
73 
74     for node in nodes:
75         # Set attribute or remove attribute
76         node.setAttribute('author', 'nonove')
77         node.removeAttribute('status')
78 
79     # Remove node 1
80     nonove.removeChild(nodes[1])
81 
82     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>

 

就先总结了这么多,有什么不对的地方或者更好的方法请赐教啊……

转载请注明原文地址啊,辛辛苦苦的总结出来的,别人的劳动成果不容易。

转载于:https://www.cnblogs.com/itaceo-o/p/3193136.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值