2016-08-02 21 views
0

我一直在研究一種解析xml文檔的方法,它在python中有多個根,但一直不成功。有沒有人知道任何有用的網站來完成這一點,或有任何看法是否可以做到這一點?我有下面的xml文件和python代碼。在我的Python代碼的讀循環中,我得到一個'NoneType'對象沒有屬性「文本」錯誤。在python中解析xml文檔和多個孫子

XML文件:

<ThursdayDay12> 

<event> 
<title>Refrigerator/freezer</title> 
<startHour>11</startHour> 
<startMinute>00</startMinute> 
<duration units = 'min'>780</duration> 
<load units = 'W'>33.77</load> 
<comment> 
'HANOVER HANRT30C Model' 
</comment> 
</event> 

<event> 
<title>Temperature</title> 
<startHour>7</startHour> 
<startMinute>30</startMinute> 
<duration units = 'min'>990</duration> 
<load units = 'W'>3520</load> 
<comment> 
'Assume AC requirement for house is 1 TR=3.52 kW' 
</comment> 
</event> 

<event> 
<title>Indoor lighting</title> 
<startHour>20</startHour> 
<startMinute>00</startMinute> 
<duration units = 'min'>240</duration> 
<load units = 'W'>250</load> 
<comment> 
'LED lighting for 4 rooms' 
</comment> 
</event> 

</ThursdayDay12> 


<FridayDay13> 

<event> 
<title>TV</title> 
<startHour>19</startHour> 
<startMinute>30</startMinute> 
<duration units = 'min'>150</duration> 
<load units = 'W'>3.96</load> 
<comment> 
'VIZIO E28h-C1 model rated at 34.7 kWh/yr' 
</comment> 
</event> 

<event> 
<title>Heat water for showers</title> 
<startHour>19</startHour> 
<startMinute>30</startMinute> 
<duration units = 'min'>150</duration> 
<load units = 'W'>1385</load> 
<comment></comment> 
</event> 

</FridayDay13> 

</SD2017NominalEnergyUse> 

Python代碼:

import xml.etree.ElementTree as ET 

tree = ET.parse('SD2017NominalEnergyUse.xml') 
root = tree.getroot() 


title, start, end, load, duration = [],[],[],[],[] 

for child in root: 
    for grandchild in child: 

     title.append(child.find('title').text) 

     sh = int(child.find('startHour').text) 
     sm = int(child.find('startMinute').text) 
     duration.append(float(child.find('duration').text)) 
     start.append(sh*60+sm) 
     end.append(start[-1] + duration[-1]) 
     load.append(float(child.find('load').text)) 

P = 0.0 
for i in range(len(root)): 
    P = P+load[i] 

print(P) 

回答

1

你試過xml.domminidom

+0

我還沒有找到有助於幫助我解析XML文件的兒童和孫子的屬性 –

+0

@ZachThomas [我如何在Python中解析XML](http://stackoverflow.com/questions/1912434/how-do- i-parse-xml-in-python) – Frangipanes

+0

是的,但它似乎沒有解決如何解析XML文件與孫子部分的文件。 etree中的解析不能與xml文件的孫子屬性配合使用 –