2015-02-07 141 views
1

我正在解析我的電影5生成的movie.xml文件以獲得電影的流派。有些電影有多種類型,如:Python ElementTree多解析XML解析

-<Genres> 
<Genre>Adventure</Genre> 
<Genre>Comedy</Genre> 
<Genre>Action</Genre> 
... 
... 
</Genres> 

我怎麼能讀它作爲一個單一變量 流派= genere1,genre2,genre3 ...

這是我在做什麼,它給了我僅僅只有第一流派:

import xml.etree.ElementTree as ET 
tree = ET.parse('movie.xml') 
root = tree.getroot() 
Genre = tree.findtext("Genres/Genre") 

縮短的movie.xml如下:

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<!--This file is created by My Movies (http://www.mymovies.dk)--> 
<Title IsBoxSetParent="False" IsBoxSetChild="False"> 
    <ID>649</ID> 
    <MediaType>Movie</MediaType> 
    <LocalTitle>Six Days, Seven Nights</LocalTitle> 
    <ProductionYear>1998</ProductionYear> 
    <ReleaseDate>12/8/1998</ReleaseDate> 
    <RunningTime>101</RunningTime> 
    <TagLine /> 
    <Genres> 
    <Genre>Adventure</Genre> 
    <Genre>Comedy</Genre> 
    <Genre>Action</Genre> 
    <Genre>Romance</Genre> 
    </Genres> 
    <AudioTracks> 
    <AudioTrack Language="English" Type="Dolby Digital" Channels="5.1" /> 
    <AudioTrack Language="French" Type="Dolby Digital" Channels="5.1" /> 
    </AudioTracks> 
    <CheckSum>f98f43ba468b519bb7e78c15b7ab9cfa</CheckSum> 
</Title> 

回答

0

您可以findall()呼叫嘗試,用map,並提取其文字和join創建一個字符串的所有結果,如:

import xml.etree.ElementTree as ET 
tree = ET.parse('movie.xml') 
root = tree.getroot() 
Genre = ', '.join(map(lambda e: e.text, tree.findall("Genres/Genre"))) 
print(Genre) 

國債收益率:

Adventure, Comedy, Action, Romance 
1

謝謝,這是比更優雅我想出了另一種方式。

genre="" 
for element in root.iter("Genre"): 
     genre = genre + ", " + ("%s" % (element.text)) 
print genre 

產生相同的: Adventure, Comedy, Action, Romance