首页 > 代码库 > [python 2.x] xml.etree.ElementTree module
[python 2.x] xml.etree.ElementTree module
XML 文件:xmlparse.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE Model SYSTEM "/var/company/user/etc/user2017.dtd"> <Model version="1" importVersion="16.2"> <Create> <Company name="Google.inc"> <Division sourceType="Personnel"> <UserName string="John Smith" /> <Sex string="Male" /> <Age int="30" /> <HireDate string="2009-07-01" /> <Station sting="Manager" /> <isMarry boolen="True" /> </Division> <Division sourceType="Personnel"> <UserName string="Mary Smith" /> <Sex string="Female" /> <Age int="23" /> <HireDate string="2017-07-01" /> <Station string="Secretary" /> <isMarry boolen="False" /> </Division> </Company> <Company name="Baidu.inc"> <Division sourceType="Personnel"> <UserName string="Alice Wang" /> <Sex string="Female" /> <Age int="29" /> <HireDate string="2002-07-01" /> <Station string="HR Manager" /> <isMarry boolen="True" /> </Division> <Division sourceType="Personnel"> <UserName string="Mark Zhou" /> <Sex string="Male" />
<Age int="20" /> <HireDate string="" /> <Station string="Intern" /> <isMarry boolen="False" /> </Division> </Company> </Create> </Model>
解析XML文件并打印每个公司每个人的年龄:testparse.py
import xml.etree.ElementTree as ET tree = ET.parse(‘xmlparse.xml‘) root = tree.getroot() for Division in root.findall(‘.//Division‘): UserName = Division.find(‘UserName‘).attrib Age = Division.find(‘Age‘).attrib print UserName, Age
输出结果:
{‘string‘: ‘John Smith‘} {‘int‘: ‘30‘} {‘string‘: ‘Mary Smith‘} {‘int‘: ‘23‘} {‘string‘: ‘Alice Wang‘} {‘int‘: ‘29‘} {‘string‘: ‘Mark Zhou‘} {‘int‘: ‘20‘}
[python 2.x] xml.etree.ElementTree module
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。