我想用Python提取XML文件中的所有文本。
有没有可能?
我听说可以使用 xml.etree.ElementTree
例如:
<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>
我只想提取: 1个 2008年 141100 4 2011年 等等...
答案 0 :(得分:0)
希望这会有所帮助
from xml-etree.ElementTree import parse
tree = parse('data.xml') #extract the file (change the name to your file name)
for e in tree.findall('year') #searches the content of all the tags 'year'
print(e.text)
您还可以将值存储在字典中,其键等于国家/地区名称,值等于所有属性的列表