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

2024-05-28 19:45:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

只是。你知道吗

我应该使用哪个函数?你知道吗


Tags: namedataxmlyearcountryrankdirectioncolombia
2条回答

你可以做:

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

安装

pip3 install lxml

代码

from lxml import etree

with open('countries.xml', 'r') as f:
    root = etree.fromstring(f.read())

neighbors = root.xpath('/data/country[@name="Liechtenstein"]/neighbor')

for n in neighbors:
    n_names = n.xpath('@name')
    n_name = n_names[0]
    n_directions = n.xpath('@direction')
    n_direction = n_directions[0]
    print(n_name, n_direction)

输出

Austria E
Switzerland W

在python3.6.0上测试。你知道吗

如果您使用python2.7:用pip替换pip3,用print n_name, n_direction替换print(n_name, n_direction)。玩得高兴。你知道吗

相关问题 更多 >

    热门问题