使用 Python 按属性查找 ElementTree 中的所有元素

Find all elements in ElementTree by attribute using Python

我有一个xml,它有很多不同的节点,标签不同,但属性相同。是否有可能找到所有这些节点?

我知道,如果所有节点都具有相同的标签,则可以通过属性找到所有节点:

root.findall(".//tag[@attrib]")

但就我而言,它们都有不同的标签。这样的东西不起作用:

root.findall(".//[@attrib]")

在 XPath 中,您可以使用 * 来引用任何名称的元素,并且可以使用 @* 来引用任何名称的属性:

root.findall(".//*[@attrib]")

旁注:

提醒一下,如果你真的在使用 lxml(不仅仅是不小心用 标记了问题),我建议使用 xpath() 方法而不是 findall()。前者有更好的 XPath 支持。例如,当您需要查找有限名称集的元素时,比如 foobar,您可以使用以下带有 xpath() 方法的 XPath 表达式:

root.xpath("//*[self::foo or self::bar][@attrib]")

上面相同的表达式传递给 findall() 时将导致错误:

SyntaxError: prefix 'self' not found in prefix map