You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python检查XML中国家的指定邻国及获取方向

Python解析XML检查邻国并生成DataFrame的正确实现

问题背景

给定如下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>

需求:

  • 检查列支敦士登是否有指定邻国(奥地利、德国)
  • 存在则获取对应方向,不存在则设为空字符串
  • 避免未定义变量错误,最终结果存入DataFrame

原代码问题分析

第一段代码错误

  • neighbor变量未定义,直接调用neighbor.attrib会触发NameError
  • 未遍历列支敦士登节点下的neighbor子节点,逻辑完全错误

第二段代码错误

  • cntr是字符串类型的国家名称,不能调用iter('neighbor'),应该使用Country.iter('neighbor')
  • 未初始化austr_dir和germ_dir为默认空字符串,若遍历中未匹配到德国,germ_dir会未定义,触发NameError

正确实现方案

import xml.etree.ElementTree as ET
import pandas as pd

# 解析XML文件,替换为你的XML文件路径
tree = ET.parse('your_xml_file.xml')
root = tree.getroot()

# 提前初始化目标变量为默认空字符串,彻底避免未定义错误
austr_dir = ''
germ_dir = ''

# 遍历所有country节点
for country in root.iter('country'):
    cntr_name = country.get('name')
    if cntr_name == 'Liechtenstein':
        # 遍历当前国家的所有neighbor子节点
        for neighbor in country.iter('neighbor'):
            nghbr_name = neighbor.get('name')
            if nghbr_name == 'Austria':
                # 第二个参数为默认值,防止节点无direction属性报错
                austr_dir = neighbor.get('direction', '')
            elif nghbr_name == 'Germany':
                germ_dir = neighbor.get('direction', '')

# 生成DataFrame
result_df = pd.DataFrame({
    'Country': ['Liechtenstein'],
    'Austria_Direction': [austr_dir],
    'Germany_Direction': [germ_dir]
})

print(result_df)

代码说明

  • 提前初始化方向变量为空字符串,从根源避免未定义变量错误
  • 通过root.iter('country')定位目标国家节点,再遍历其下属的neighbor子节点
  • 使用get方法的第二个参数设置默认值,即使节点缺少direction属性也不会报错
  • 最后将结果整理为字典格式,传入pd.DataFrame生成结构化表格

内容的提问来源于stack exchange,提问作者ASAS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:51:51