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

如何用Python+BeautifulSoup提取XML中指定Name对应的Value值?

解决BeautifulSoup解析XML时根据提取对应的问题

核心思路是以每个标签为单位处理,它是和的天然容器,不要单独提取所有Name/Value标签再匹配,避免出现错位问题。

方法一:构建键值对字典(适合多次查询)

先把所有里的Name和Value整理成字典,之后直接通过键名取值即可:

from bs4 import BeautifulSoup

# 替换成你的XML内容
xml_content = """
<AdditonalAttributes>
    <Attribute>
        <Name>Occupation</Name>
        <Value>Unknown</Value>
    </Attribute>
    <Attribute>
        <Name>CarrierCode</Name>
        <Value>656</Value>
    </Attribute>
</AdditonalAttributes>
"""

# 解析XML必须指定"xml"解析器
soup = BeautifulSoup(xml_content, "xml")

attr_map = {}
for attr in soup.find_all("Attribute"):
    name = attr.find("Name").text.strip()
    value = attr.find("Value").text.strip()
    attr_map[name] = value

# 直接通过Name取值
print(attr_map["Occupation"])    # 输出 Unknown
print(attr_map["CarrierCode"])   # 输出 656

方法二:直接定位单个值(适合单次查询)

如果只需要找某一个特定Name对应的Value,不用构建字典,直接链式查找:

# 找到内容为Occupation的<Name>标签,再取它的下一个兄弟<Value>
occupation_val = soup.find("Name", string="Occupation").find_next_sibling("Value").text.strip()
print(occupation_val)

# 或者通过父节点<Attribute>定位
carrier_val = soup.find("Name", string="CarrierCode").parent.find("Value").text.strip()
print(carrier_val)

注意事项

  • 必须用"xml"作为BeautifulSoup的解析器,默认的HTML解析器处理XML标签可能出现异常
  • 如果存在多个同名的,find()只会返回第一个匹配项,用find_all()可以获取所有结果后再遍历处理
  • 用strip()去除文本前后的空白,避免因XML格式缩进导致的无效字符

内容的提问来源于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 14:54:19