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
相关产品推荐
相关产品推荐

