python读取xml(二)

ElementTree(元素树)读取xml

1.引包

from xml.etree import ElementTree

2.定义一个xml文件
xmlTest.xml



    
        7369
        SMITH
        CLERK
    
    
        7499
        ALLEN
        SALESMAN
    
    
        7566
        JONES
        MANAGER
    
    
        75662
        JONES2
        MANAGER2
        33
    

3.用ElementTree读取xml文件
ElementTree就像一个轻量级的DOM,具有方便友好的API。代码可用性好,速度快,消耗内存少

#xmlTest2.py

from xml.etree import ElementTree

filename = "xmlTest.xml"
###2.ElementTree
print "2.ElementTree"
root2 = ElementTree.parse(filename) # read xml file
#root2 = ElementTree.fromstring(text) # read string

lst_node = root2.getiterator("emp")
for emp in lst_node:
    print "emp.attrib:%s" % emp.attrib
    if emp.attrib.has_key('sex') > 0 :
        print "emp.attrib['sex']:%s" % emp.attrib['sex']
    for child in emp.getchildren():
        print child.tag, ":", child.text
    print "#################"

4.显示结果

D:\pyProjects>python xmlTest2.py
2.ElementTree
emp.attrib:{'id': '0', 'sex': 'male'}
emp.attrib['sex']:male
empno : 7369
ename : SMITH
job : CLERK
#################
emp.attrib:{'id': '1', 'sex': 'female'}
emp.attrib['sex']:female
empno : 7499
ename : ALLEN
job : SALESMAN
#################
emp.attrib:{'id': '2'}
empno : 7566
ename : JONES
job : MANAGER
#################
emp.attrib:{'id': '3'}
empno : 75662
ename : JONES2
job : MANAGER2
age : 33
#################

D:\pyProjects>

你可能感兴趣的:(python,xml)