码迷,mamicode.com
首页 > 编程语言 > 详细

[python 2.x] xml.etree.ElementTree module

时间:2017-05-22 19:04:11      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:attr   name   logs   imp   xml文件   company   system   log   string   

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

标签:attr   name   logs   imp   xml文件   company   system   log   string   

原文地址:http://www.cnblogs.com/jenneyforis/p/6890766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!