1

我在 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>
4

1 回答 1

0

使用xml.etree

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

打印根的孩子

>>> 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'}
于 2013-05-03T08:47:05.273 回答