Python中如何读取xml的数据?

  <?xml version="1.0" encoding="utf-8" ?> 
- <catalog>
  <maxid>4</maxid> 
- <login username="pytest" passwd="123456">
  <caption>Python</caption> 
- <item >
  <caption>test</caption> 
  </item>
  </login>
- <item >
  <caption>Zope</caption> 
  </item>
  </catalog>

处理的xml文件如上图:

Python代码:

#coding =utf-8
import xml.dom.minidom
dom=xml.dom.minidom.parse('D:\Python27\lianxidanma\info.xml')
root=dom.documentElement

login=root.getElementsByTagName('login')
logins=login[0]
username=logins.getAttribute('username')
print username
password=logins.getAttribute('passwd')
print password

captions=root.getElementsByTagName('caption')
#c1=captions[0]
#print c1.firstChild.data
print len(captions)

for i in range(len(captions)):
        print captions[i].firstChild.data

xml.dom.minidom 模块被用来处理xml文件,所以要先引入。

xml.dom.minidom.parse() 用于打开一个xml文件,并将这个文件对象dom变量。

documentElement 用于得到dom对象的文档元素,并把获得的对象给root

getElementsByTagName()用于获取标签

getAttribute()根据标签获取标签中的属性值

firstChild.data根据标签获取标签之间的值