Python解析带命名空间XML时出现NoneType可迭代错误求助
问题:xml.etree.ElementTree的find方法返回None无法找到目标节点
我使用Python的xml.etree.ElementTree解析带命名空间的XML数据,通过嵌套遍历确认节点层级为:
{http://www.w3.org/2003/05/soap-envelope}Body {http://www.onvif.org/ver10/search/wsdl}GetRecordingSummaryResponse {http://www.onvif.org/ver10/search/wsdl}Summary
但尝试直接用find方法查找Summary节点时返回None,执行以下代码:
for child in xmlRoot.find('{http://www.onvif.org/ver10/search/wsdl}Summary'): NumberRecordings=child.find('{http://www.onvif.org/ver10/schema}NumberRecordings') print(NumberRecordings.text)
出现报错:
TypeError: 'NoneType' object is not iterable
原因分析
find方法仅会查找当前节点的直接子节点,而Summary节点并非xmlRoot的直接子节点,它处于Body → GetRecordingSummaryResponse的层级之下,直接从根节点调用find无法定位到目标节点,因此返回None。
解决方法
方法1:逐层定位节点
按照节点层级依次查找,确保每一步都获取到正确的父节点:
# 定位到Body节点 body = xmlRoot.find('{http://www.w3.org/2003/05/soap-envelope}Body') # 定位到GetRecordingSummaryResponse节点 response = body.find('{http://www.onvif.org/ver10/search/wsdl}GetRecordingSummaryResponse') # 定位到Summary节点 summary = response.find('{http://www.onvif.org/ver10/search/wsdl}Summary') # 遍历Summary子节点并查找目标内容 for child in summary: number_recordings = child.find('{http://www.onvif.org/ver10/schema}NumberRecordings') if number_recordings is not None: print(number_recordings.text)
方法2:使用XPath表达式配合命名空间映射
通过定义命名空间映射,使用XPath直接跨层级定位节点,更简洁高效:
# 定义命名空间映射 ns_map = { 'soap': 'http://www.w3.org/2003/05/soap-envelope', 'search': 'http://www.onvif.org/ver10/search/wsdl', 'schema': 'http://www.onvif.org/ver10/schema' } # 直接定位到NumberRecordings节点 number_recordings = xmlRoot.find( './/soap:Body/search:GetRecordingSummaryResponse/search:Summary/schema:NumberRecordings', ns_map ) if number_recordings is not None: print(number_recordings.text)
如果需要遍历Summary下的所有子节点,也可以简化为:
summary = xmlRoot.find('.//search:Summary', ns_map) for child in summary: nr_node = child.find('schema:NumberRecordings', ns_map) if nr_node: print(nr_node.text)
内容的提问来源于stack exchange,提问作者most.of.a.shark
相关产品推荐
相关产品推荐

