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

如何将XML解析出的子节点结果分配给对应唯一变量?

解析XML同级节点并将结果赋值给对应变量

你已经能从<AdditonalAttributes>下的同级<Attribute>节点中解析出指定名称的属性值,现在需要把这些值分别赋值给对应的独立变量(比如将Unknown赋值给Occupation,656赋值给CarrierCode)。以下是两种实用的实现方式:

方法1:直接条件判断赋值

适合属性名称固定且数量不多的场景,直接在循环中匹配名称完成赋值:

from bs4 import BeautifulSoup
xml='''
<AdditonalAttributes>
    <Attribute>
        <Name> Occupation </Name> 
        <Value> Unknown </Value>
    </Attribute>
    <Attribute>
        <Name> CarrierCode </Name>
        <Value> 656 </Value>
    </Attribute>
</AdditonalAttributes>
'''

soup = BeautifulSoup(xml, 'xml')

# 初始化目标变量
Occupation = None
CarrierCode = None

for a in soup.select('Attribute'):
    attr_name = a.Name.get_text(strip=True)
    attr_value = a.Value.get_text(strip=True)
    if attr_name == 'Occupation':
        Occupation = attr_value
    elif attr_name == 'CarrierCode':
        CarrierCode = attr_value

# 验证变量值
print(Occupation)  # 输出: Unknown
print(CarrierCode) # 输出: 656

方法2:字典统一存储(扩展性更强)

如果后续可能新增属性,用字典存储更易维护,之后可按需提取为独立变量:

from bs4 import BeautifulSoup
xml='''
<AdditonalAttributes>
    <Attribute>
        <Name> Occupation </Name> 
        <Value> Unknown </Value>
    </Attribute>
    <Attribute>
        <Name> CarrierCode </Name>
        <Value> 656 </Value>
    </Attribute>
</AdditonalAttributes>
'''

soup = BeautifulSoup(xml, 'xml')

attr_store = {}
target_attrs = ['Occupation', 'CarrierCode']

for a in soup.select('Attribute'):
    attr_name = a.Name.get_text(strip=True)
    attr_value = a.Value.get_text(strip=True)
    if attr_name in target_attrs:
        attr_store[attr_name] = attr_value

# 从字典提取为独立变量
Occupation = attr_store.get('Occupation')
CarrierCode = attr_store.get('CarrierCode')

print(Occupation)  # 输出: Unknown
print(CarrierCode) # 输出: 656

两种方式对比

  • 方法1逻辑直观,代码简洁,适合属性数量少且固定的场景;
  • 方法2可扩展性强,新增属性仅需修改target_attrs列表,无需改动赋值逻辑,更适合属性较多或动态变化的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:06:17