Python如何从XML文档中提取指定字段内容 如获取值为Are的节点内容
原代码错误点
getElementsByTagName()仅接收标签名作为参数,你传入包含属性的parameter name是错误写法,正确的标签名只有parameter- 缺少目标内容的筛选判断逻辑,所以会返回所有匹配到的标签元素
修正代码(匹配内容为「Are」的需求)
假设你使用的是Python标准库xml.dom.minidom,调整后代码如下:
# 先获取所有<parameter>标签元素 items = mydoc.getElementsByTagName('parameter') target_content = "" target_name_attr = "" for item in items: # 提取标签内文本,去除前后空白字符 current_content = item.firstChild.data.strip() # 匹配目标内容 if current_content == "Are": target_content = current_content target_name_attr = item.attributes['name'].value # 匹配到目标后可直接退出循环,节省性能 break # 按需使用匹配到的结果 print(f"对应name属性值:{target_name_attr},字段内容:{target_content}")
补充:按name属性筛选「Task Name」的场景
如果你实际需求是提取name="Task Name"的标签内容,可调整为以下逻辑:
items = mydoc.getElementsByTagName('parameter') target_content = "" for item in items: current_name = item.attributes['name'].value if current_name == "Task Name": target_content = item.firstChild.data.strip() break print(target_content)
内容的提问来源于stack exchange,提问作者The Doctor
相关产品推荐
相关产品推荐

