XML文件的部分:使用Python xmltodict閱讀第三標籤
<?xml version="1.0" encoding="UTF-8"?>
<Station>
<Code>HT</Code>
<Type>knooppuntIntercitystation</Type>
<Namen>
<Kort>Den Bosch</Kort>
<Middel>'s-Hertogenbosch</Middel>
<Lang>'s-Hertogenbosch</Lang>
</Namen>
<Land>NL</Land>
<Synoniemen>
<Synoniem>Hertogenbosch ('s)</Synoniem>
<Synoniem>Den Bosch</Synoniem>
</Synoniemen>
</Station>
<Station>
<Code>ALMO</Code>
<Type>stoptreinstation</Type>
<Namen>
<Kort>Oostvaard</Kort>
<Middel>Oostvaarders</Middel>
<Lang>Almere Oostvaarders</Lang>
</Namen>
<Land>NL</Land>
<Synoniemen></Synoniemen>
</Station>
<Station>
<Code>ATN</Code>
<Type>stoptreinstation</Type>
<Namen>
<Kort>Aalten</Kort>
<Middel>Aalten</Middel>
<Lang>Aalten</Lang>
</Namen>
<Land>NL</Land>
<Synoniemen></Synoniemen>
</Station>
<Station>
<Code>ASA</Code>
<Type>intercitystation</Type>
<Namen>
<Kort>Amstel</Kort>
<Middel>Amsterdam Amstel</Middel>
<Lang>Amsterdam Amstel</Lang>
</Namen>
<Land>NL</Land>
<Synoniemen></Synoniemen>
</Station>
我的Python代碼閱讀XMLFILE:
import xmltodict
def leesXML(filename):
with open(filename) as mijnXMLBestand:
inhoud = mijnXMLBestand.read()
xmldictionary = xmltodict.parse(inhoud)
return xmldictionary
stationsdictionary = leesXML('stations.xml')
stations = stationsdictionary['Stations']['Station']
def program():
for station in stations:
type = station['Type']
Code = station['Code']
print(Code + ' - ' + type)
print('Dit zijn de codes en types van de 4 stations:')
program()
用程序( )我會得到一個類型和列表代碼標記出來的XML文件。
現在,我試圖找出如何讓郎標記出來,並做出similair列表像一個以上,但只有代碼和郎標籤
我做了一個新的變量:
thirdtag = stationsdictionary['Stations']['Station']['Namen']
當我打印這我得到一個錯誤
TypeError: list indices must be integers or slices, not str
誰能說什麼我做錯了嗎?請使用簡單易讀的Python代碼。我是一名學生,開始學習python。
感謝
請你分享一個完整的文件例子嗎? –
好吧,我只是改變了它。 –