简体   繁体   English

python中的XML树遍历

[英]XML Tree traversal in python

I am traversing an XML file in Python like this: 我正在Python中遍历这样的XML文件:

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

My output is: 我的输出是:

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

Now I want to save only names which are just above Int_Class_ID like this: 现在,我只Int_Class_ID这样保存仅在Int_Class_ID上方的名称:

Student
Address
Seminar

Can some one help? 可以帮忙吗?

My XML file is like this: 我的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>

using xml.etree ! 使用xml.etree

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

Print children of root with 用以下命令打印root的子级

>>> for child in root:
...   print child.tag, child.attrib

With this input xml file 有了这个输入的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>

command gives 命令给

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM