【发布时间】:2018-07-23 11:01:16
【问题描述】:
我想通过xml.etree.ElementTree将xml文件转换为excel。
我想从特定的根目录读取数据。
假设我的 xml 看起来像
<?xml version="1.0"?>
<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>
如果我直接使用'iter',我会得到:
for neighbor in root.iter('neighbor'):
print neighbor.attrib
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Malaysia', 'direction': 'N'}
{'name': 'Costa Rica', 'direction': 'W'}
{'name': 'Colombia', 'direction': 'E'}
但我只想得到'列支敦士登'的所有邻居 这意味着我希望我的脚本给我
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
只有。
我应该使用哪个函数?
【问题讨论】:
-
21.5.2. XPath 支持阅读文档 我认为这是最好的选择。和w3schools.com/xml/xpath_intro.asp
标签: python xml excel elementtree