首页 > 代码库 > [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