我有一个包含多个命名空间的 xml。 我想迭代 namespace = ' http://ns.example.com/xmto/ 的元素'
我正在使用带有 ElementTree 的 Python 3.4
此代码显示元素1:
tree.findall("{http://ns.example.com/xpto/}element1")
我想找到具有此 namespace 的所有元素。 像这样的东西:
tree.findall("{http://ns.example.com/xpto/}:*")
这可能吗? 或者唯一的方法是检查每个元素上的 element.tag?
最佳答案
如果您要使用lxml.etree
,则可以使用 XPath 的 namespace-uri()函数,类似这样:
elements = tree.xpath('//*[namespace-uri() = "http://ns.example.com/xpto/"]')
不幸的是,xml.etree
中的 XPath 支持不支持 namespace-uri
函数。可能其他人会提出与 native xml 模块配合使用的解决方案,但我喜欢使用 xpath 支持 lxml
。
关于python - 查找命名空间内的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46008518/