我創建了一個模型,用於使用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文件中的所有五個鄰居元素。這是爲什麼發生?
這是因爲您使用的是類屬性,而不是實例屬性。 – ekhumoro