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

Python3使用minidom提取XML中house标签下residents值求和

解决方法

核心逻辑

你之前得到总和12的原因是直接调用了文档全局的getElementsByTagName('residents')方法,会匹配XML中所有residents标签,自然包含了apartment节点下的数值。我们只需要调整查询范围:先筛选所有house节点,再在每个house节点的内部查找residents子节点,即可实现范围限定。

完整实现代码

from xml.dom import minidom

# 1. 加载XML内容(如果是读取本地XML文件,替换为minidom.parse('你的文件路径')即可)
xml_content = """
<city>
   <house>
       <color>red</color>
       <residents>3</residents>
   </house>
   <house>
       <color>yellow</color>
       <residents>5</residents>
   </house>
   <apartment>
       <color>blue</color>
       <residents>4</residents>
   </apartment>
</city>
"""
dom = minidom.parseString(xml_content)

total = 0
# 2. 先获取文档内所有house节点
house_nodes = dom.getElementsByTagName('house')
for house in house_nodes:
    # 3. 仅在当前house节点的子节点范围内查找residents标签
    resident_nodes = house.getElementsByTagName('residents')
    if resident_nodes: # 兼容house下无residents标签的异常场景
        resident_num = int(resident_nodes[0].firstChild.data.strip())
        total += resident_num

print(f"house内总人口:{total}")

运行结果

输出为house内总人口:8,符合预期。


内容的提问来源于stack exchange,提问作者moonlight-hollow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:45:02