2016-01-20 40 views
1

我创建了一个模型,用于使用ElementTree从xml文件中收集数据来创建对象,以解析xml文件。我的项目有几千行代码,但我可以使用下面的示例快速重现我的问题。为什么Elementtree迭代每个元素,即使它不是孩子?

示例XML数据:

<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> 

型号:

class neighbor(object): 
    name = "" 
    direction = "" 

class neighborList(object): 
    neighbor = [] 

class country(object): 
    name = "" 
    rank = "" 
    year = "" 
    gdppc = "" 
    neighborList = neighborList() 

class countryList(object): 
    country = [] 

class data(object): 
    countryList = countryList() 

分析器:

from xml.etree import ElementTree as ET 
    import countries_model as ctry 

    def CountriesCrusher(filename): 

     xmldoc = ET.parse(filename) 
     element = xmldoc.getroot() 

     _data = ctry 
     _countryList = ctry.countryList() 

     for firstLevel in element.findall('country'): 
      b = ctry.country() 
      b.rank = firstLevel.find('rank').text 
      b.year = firstLevel.find('year').text 
      b.gdppc = firstLevel.find('gdppc').text 
      b.neighborList = ctry.neighborList() 

      for secondLevel in firstLevel.findall('neighbor'): 
       c = ctry.neighbor 
       c.direction = secondLevel.attrib.get('direction') 
       c.name = secondLevel.attrib.get('name') 
       b.neighborList.neighbor.append(c) 

      _countryList.country.append(b) 

     a = ctry.data() 
     a.countryList = _countryList 
     _data = a 
     return _data 

    ictry = CountriesCrusher('countries.xml') 

我运行此之前,我会想到,如果我看ictry.countryList.country我会看到三个条目,如果我看看ictry.countryList.country[0].neighborList.neighbor我会看到两个邻居条目该国家,而是我看到整个XML文件中的所有五个邻居元素。这是为什么发生?

+0

这是因为您使用的是类属性,而不是实例属性。 – ekhumoro

回答

1

您尚未使用类country的实例属性。

撰写您country类(和所有其他人),像这样:

class country: 
    def __init__(self): 
     self.name = "" 
     self.rank = "" 
     self.year = "" 
     self.gdppc = "" 
     self.neighborList = neighborList() 

现在b = ctry.country()会给你一个实例,其属性将被分离/从第二次调用b = ctry.country()分开。您当前的方法ctry.country的所有实例共享相同的属性,因为它们是类属性,而不是实例属性。

查看更多about class vs instance attributes here

+0

感谢您的快速回复。这解决了我的问题。 – btathalon

相关问题