原文地址: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>
就先總結了這么多,有什么不對的地方或者更好的方法請賜教啊……
轉載請注明原文地址啊,辛辛苦苦的總結出來的,別人的勞動成果不容易。