gpt4 book ai didi

python - 如何获取XML中特定根的数据(通过python)

转载 作者:行者123 更新时间:2023-12-01 01:44:56 26 4
gpt4 key购买 nike

我想通过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'}

仅。

我应该使用哪个函数?

最佳答案

你可以这样做:

x = """<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>
"""

import xml.etree.ElementTree as ET
data = ET.fromstring(x) //here x is xml string
for child in data:
if child.attrib['name'] == 'Liechtenstein':
for grandchild in child:
if grandchild.tag == 'neighbor':
print grandchild.attrib

关于python - 如何获取XML中特定根的数据(通过python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51477245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com