python中xml的操作可以使用dom库、sax库、etree库(这个是新的)、parsers库。其中dom.minidom是dom轻量级模块,这里介绍dom.minidom和etree两个模块这里以UserInfo.xml文件为例,xml
内容如下:
xml解析
>>>xmldoc = minidom.parse('UserInfo.xml') #it will load a xml file,can use filename or openobject
>>>xmldoc
>>>print xmldoc.toxml() #output all xml
George
John
Reminder
magicdmer
>>>node = xmldoc.firstChild
>>>print node.toxml()
George
John
Reminder
magicdmer
>>>print node.firstChild.toxml() #this will display blank,because it find '\n'
>>>print node.childNodes[1].toxml()
George
>>>print node.childNodes[2].toxml() #it is '\n', display blank
>>>print node.childNodes[3].toxml()
John
>>>print node.lastChild.toxml() #it find zuihou element,it is '\n'>>>
搜索元素
>>>from xml.dom import minidom
>>>xmldoc = minidom.parse('UserInfo.xml')
>>>FindIt = xmldoc.getElementsByTagName('name') #it return Element Object
>>>print FindIt[0].toxml()
magicdmer
>>>print FindIt[0].tagName
name
>>>
访问元素属性
类似<ref id="bit">
0
1
>>>from xml.dom import minidom
>>>xmldoc = minidom.parse('UserInfo.xml')
>>>FindIt = xmldoc.getElementsByTagName('ref') #it return Element Object
>>>It = FindIt[0]>>>It.attributes.keys()
[u'id']
>>>It.attributes.values()
[]
>>>It.attributes["id"]
[]
>>>print It.attributes["id"].name
u'id'
>>>print It.attributes["id"].value
u'bit'
>>>from xml.etree.ElementTree import ElementTree
>>>tree = ElementTree()
>>>tree.parse('UserInfo.xml')
>>>p = tree.find('name')
>>>print p.text
magicdmer
>>>print p.tag
name
>>>