python - 查找命名空间内的所有元素

标签 python xml-parsing

我有一个包含多个命名空间的 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/

相关文章:

python selenium 单击链接

Python 3 HTTP Server 发送 header 作为输出

python - 如何在 Django 模板中获取站点名称?

用于计算循环执行的 Python 习惯用法

python + libxml2 : Sorting XML node's elements according to attribute's value

java - 对 XML 节点的 getNodeName() 操作返回 #text

python - UnboundLocalError : local variable 'x' referenced before assignment in Discord. py

Python - 读取字符串中的空格分隔数字

java - 究竟是什么选择了这个 XPath 查询?

JSF 在 SVG 之后吞下结束标记