2016-01-20 32 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

相關問題