Python树中的XML树遍历

时间:2013-05-03 08:19:29

标签: python xml-parsing

我在Python中遍历XML文件:

for node in rootNode1.iter():
    print node.tag

我的输出是:

Student
Int_Class_ID
Name
StudentID
EmailID
Address
Int_Class_ID
Street
City
PostalCode
Seminar
Int_Class_ID
SeminarNumber
Course

现在我只想保存像Int_Class_ID这样的名字:

Student
Address
Seminar

有人能帮忙吗?

我的XML文件是这样的:

<?xml version='1.0' encoding='UTF-8'?>
<ModelDiff>
  <Student>
    <Int_Class_ID>1</Int_Class_ID>
    <Name>A</Name>
    <StudentID>1</StudentID>
    <EmailID>br</EmailID>
    <Address>
      <Int_Class_ID>3</Int_Class_ID>
      <Street>c</Street>
      <City>P</City>
      <PostalCode>d</PostalCode>
    </Address>
    <Seminar>
      <Int_Class_ID>4</Int_Class_ID>
      <SeminarNumber>e</SeminarNumber>
      <Course type="f">
        <Int_Class_ID>11</Int_Class_ID>
        <TopicName>g</TopicName>
        <Day>Monday</Day>
        <Date>15/04/2013</Date>
      </Course>
  </Student>

1 个答案:

答案 0 :(得分:0)

使用xml.etree

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

使用

打印root用户
>>> for child in root:
...   print child.tag, child.attrib

使用此输入xml文件

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

命令给出

>>> for child in root:
...   print child.tag, child.attrib
...
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}