如何在列表中查找具有属性的元素?
How can I find elements with attributes within a list?
如何在 python 上使用 lxml 查找具有不同属性的元素?
例如
<Form>
<Subform ind="0">
<Check ind="0">0</Check>
<Check ind="1">1</Check>
<Check ind="2">2</Check>
<Check ind="3">3</Check>
</Subform>
</Form>
检索我做的支票:
tree.findall("./Form/Subform/Check")
获得第一:
tree.findall("./Form/Subform/Check[@ind='0']")
但我想做的是
tree.findall("./Form/Subform/Check[@ind='0' or @ind='1']")
只检索第一个和第二个(或第一个和最后一个)
我如何使用 lxml 做到这一点?
tree.findall("./Form/Subform/Check[@ind='0' or @ind='1']")
表达式有效,这将在 lxml
和 xpath()
方法中起作用。如果你想"scalable",你可以动态构造表达式:
values = ["0", "1"]
condition = " or ".join("@ind = '%s'" % value for value in values)
print(root.xpath("//Subform/Check[%s]" % condition))
该表达式是正确的,但您需要使用提供完整 XPath 1.0 支持的 xpath()
方法。 findall()
只支持有限的 XPath 子集,正如 xml.etree.ElementTree
所做的那样:
tree.xpath("/Form/Subform/Check[@ind='0' or @ind='1']")
如何在 python 上使用 lxml 查找具有不同属性的元素?
例如
<Form>
<Subform ind="0">
<Check ind="0">0</Check>
<Check ind="1">1</Check>
<Check ind="2">2</Check>
<Check ind="3">3</Check>
</Subform>
</Form>
检索我做的支票:
tree.findall("./Form/Subform/Check")
获得第一:
tree.findall("./Form/Subform/Check[@ind='0']")
但我想做的是
tree.findall("./Form/Subform/Check[@ind='0' or @ind='1']")
只检索第一个和第二个(或第一个和最后一个)
我如何使用 lxml 做到这一点?
tree.findall("./Form/Subform/Check[@ind='0' or @ind='1']")
表达式有效,这将在 lxml
和 xpath()
方法中起作用。如果你想"scalable",你可以动态构造表达式:
values = ["0", "1"]
condition = " or ".join("@ind = '%s'" % value for value in values)
print(root.xpath("//Subform/Check[%s]" % condition))
该表达式是正确的,但您需要使用提供完整 XPath 1.0 支持的 xpath()
方法。 findall()
只支持有限的 XPath 子集,正如 xml.etree.ElementTree
所做的那样:
tree.xpath("/Form/Subform/Check[@ind='0' or @ind='1']")