import xml.etree.ElementTree as ET
tree: ET = ET.parse(file)
tree.find('.//ns1:tag/@someattribute', ns)
导致{KeyError}'@',据我所知xpath表达式是正确的,元素树中是否有任何方法可以直接使用xpath而不使用.attrib获取属性值
XPath表达式在语法上是可以的。问题在于find()
仅定位元素。它不能用于查找属性。
这应该工作:
attr = tree.find('.//ns1:tag', ns).get('someattribute')
使用lxml,您可以使用xpath()
方法(返回列表):
attr = tree.xpath('.//ns1:tag/@someattribute', namespaces=ns)[0]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句