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

如何从带命名空间的XML文件中提取嵌套值?

问题原因
  • 命名空间使用错误:只有根节点<go-home-1:GOHOMEV1>绑定了go-home-1命名空间,其余子节点均未绑定该命名空间,不需要在路径中添加go-home-1前缀。你给所有路径节点都加了该前缀,导致无法匹配到对应节点,find()返回None后调用.text就抛出AttributeError,findall()返回空列表。
  • 嵌套查询路径错误:你查询B时,item1已经是<NR>节点,不需要再写从根节点开始的全路径,直接查询当前节点下的<SRng>子节点即可。
  • 代码缩进错误:for item2循环下的代码没有正确缩进,运行会触发语法错误。
修正后代码
import xml.etree.ElementTree as ET

filename = "file.xml"
namespaces = {
    "go-home-1": "https://sample.com/GO-HOME-V1"
}

root = ET.parse(filename).getroot()

# 根节点的直接子节点未绑定命名空间,不需要加前缀
sgo = root.find("HOMEV1FileHeader/SGO", namespaces).text  

A = root.findall(
    "OI/NL/NT[1]/NTData/RIS/RI/E4NS/GNS/RD/NR", namespaces)

for item1 in A:
    Result = [sgo]
    cc = item1.find("CC", namespaces).text
    ndc = item1.find("NDC", namespaces).text
    Result.append(cc)
    Result.append(ndc)
    
    # 直接查询当前NR节点下的SRng子节点即可
    B = item1.findall("SRng", namespaces)
    
    for item2 in B:
        RngStart = item2.find("SRngStart", namespaces).text
        RngStop = item2.find("SRngStop", namespaces).text
        Result.append(RngStart)
        Result.append(RngStop)

    print(Result)
运行输出
['YIFG', '9012', '411', '000', '999']
['YIFG', '834', '101', '150', '295']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 08:36:06