XML文件的读取----cElementTree
XML文件如下:
<?xml version="1.0" encoding="UTF-8"?> <tokenxml> <tokenspec> <spec id="TOTP01"> <otplen>6</otplen> <intervaltime>60</intervaltime> <updateresplen>0</updateresplen> <puk1len>0</puk1len> </spec> </tokenspec> <tokenlist> <token sn="rere0000000000" specid="TOTP01"> <seed>DDC31A7804A2DBD200BD12C9E752A5E5556FF4C28760DA8A92D368B4B07D7E5B</seed> <iv>8CAC8153F5AF7BCE0F9BAF6E5BC7D69C</iv> <mac>A60D6FF6E2720832DF5175D097A03362</mac> </token> <token sn="rere0000000001" specid="TOTP01"> <seed>0D6DED7C98F5963B6680BF48F077267307D2FC3D62475A9C0AAB2AC2F600751F</seed> <iv>D21A12C40112DFEB2C956636A394436D</iv> <mac>5683728982A0B89FFDB1F6F7F6D83062</mac> </token> <token sn="rere0000000002" specid="TOTP01"> <seed>5C432634DB6EED8AFC06CFE9199C119BF056E7B405D5CF00F357EE52E6779CF1</seed> <iv>89ACBD17D31DADD65861999BD4617BFE</iv> <mac>3762E2ABEAA26B5A40CC327B61B3736C</mac> </token> <token sn="rere0000000099" specid="TOTP01"> <seed>62A367C274AE995157A10D2A45C05928C10DB17B1E7B8538C29E211CE00210BB</seed> <iv>23967F8C156728E33A4DED3FD320C478</iv> <mac>3CDD4CB5A67822E4ED13B27D205A07F0</mac> </token> </tokenlist> </tokenxml>
读取XML代码:
def xmltest(xmlFile): import xml.etree.cElementTree as ET#cElementTree是ElementTree的C实现版本,速度更快 tree = ET.parse(xmlFile) root = tree.getroot() print root.tag, "---", root.attrib #for elem in tree.iter(tag='token'):#此方法和下面的方法结果一致,范围比较大 for elem in root.find('tokenlist').findall('token'):#此方法精确到具体的元素 print elem.tag,':', elem.attrib print "sn:%s, specid:%s" % (elem.get('sn'), elem.get('specid')) print " seed:", elem.find("seed").text print " iv:", elem.find("iv").text print " mac:", elem.find("mac").text print
if __name__ == '__main__':
xmltest('C:\\Users\\tester_cp\\Desktop\\test.xml')
结果:
tokenxml --- {} token : {'specid': 'TOTP01', 'sn': 'rere0000000000'} sn:rere0000000000, specid:TOTP01 seed: DDC31A7804A2DBD200BD12C9E752A5E5556FF4C28760DA8A92D368B4B07D7E5B iv: 8CAC8153F5AF7BCE0F9BAF6E5BC7D69C mac: A60D6FF6E2720832DF5175D097A03362 token : {'specid': 'TOTP01', 'sn': 'rere0000000001'} sn:rere0000000001, specid:TOTP01 seed: 0D6DED7C98F5963B6680BF48F077267307D2FC3D62475A9C0AAB2AC2F600751F iv: D21A12C40112DFEB2C956636A394436D mac: 5683728982A0B89FFDB1F6F7F6D83062 token : {'specid': 'TOTP01', 'sn': 'rere0000000002'} sn:rere0000000002, specid:TOTP01 seed: 5C432634DB6EED8AFC06CFE9199C119BF056E7B405D5CF00F357EE52E6779CF1 iv: 89ACBD17D31DADD65861999BD4617BFE mac: 3762E2ABEAA26B5A40CC327B61B3736C token : {'specid': 'TOTP01', 'sn': 'rere0000000099'} sn:rere0000000099, specid:TOTP01 seed: 62A367C274AE995157A10D2A45C05928C10DB17B1E7B8538C29E211CE00210BB iv: 23967F8C156728E33A4DED3FD320C478 mac: 3CDD4CB5A67822E4ED13B27D205A07F0