XML Etree解析同名<Attribute>标签返回空值问题求助
解决XML Etree解析同名标签返回空值的问题
我猜你大概率是在遍历节点或者XML结构上踩坑了——首先得提个关键点:XML必须有一个根节点,你给出的示例片段没有根元素,直接放多个<Attribute>是不符合XML规范的,这可能是解析失败返回空值的首要原因。先把你的XML补全成合法结构:
<Attributes> <Attribute> <Name>Column1</Name> <Value>abcded</Value> </Attribute> <Attribute> <Name>Column2</Name> <Value>abcdef</Value> </Attribute> <Attribute> <Name>column3</Name> <Value>abcdef</Value> </Attribute> </Attributes>
接下来看你的代码问题,你提到用了parsed_xml.it...,估计是遍历方式不对。给你一个能正常工作的Python xml.etree.ElementTree示例代码:
import xml.etree.ElementTree as ET # 可以从文件加载,这里用字符串示例 xml_str = """ <Attributes> <Attribute> <Name>Column1</Name> <Value>abcded</Value> </Attribute> <Attribute> <Name>Column2</Name> <Value>abcdef</Value> </Attribute> <Attribute> <Name>column3</Name> <Value>abcdef</Value> </Attribute> </Attributes> """ # 解析XML获取根节点 root = ET.fromstring(xml_str) # 遍历所有<Attribute>节点 for attr_node in root.findall('Attribute'): # 提取Name和Value的文本内容 attr_name = attr_node.find('Name').text attr_value = attr_node.find('Value').text print(f"找到属性:{attr_name} = {attr_value}")
这里几个要注意的点:
- 必须确保解析后的
root是合法的根节点(比如上面的<Attributes>),否则findall找不到目标节点 - 每个
<Attribute>节点内部,用find('Name')和find('Value')精准定位子节点,再通过.text获取文本内容 - 检查拼写!你示例里写的是
coumn3(少了个l),如果代码里是按column3查找的话,肯定会返回空值,大小写和拼写必须完全匹配 - 如果你的XML带有命名空间,那需要在节点名前加上命名空间前缀,比如
root.findall('{http://your-namespace}Attribute')
按照这个方式调整,应该就能正常获取到<Value>的内容了。
内容的提问来源于stack exchange,提问作者DataDog
相关产品推荐
相关产品推荐

