问题描述
在我的 xml 文件中,我有这样的节点:
In my xml file, I have nodes like this:
<waitingJobs idList="J03ac2db8 J03ac2fb0"/>
我知道如何使用 .findall
来搜索属性,但现在看来我需要使用正则表达式,因为 我不能只使用
I know how to use .findall
to search for attributes but now, it looks like I would need to use regular expressions because I can't just use
root.findall('./[@attrib='value']')
我必须使用
root.findall('./[@attrib='*value*']')
问题
- 这可以用
xml.etree
实现吗? - 你如何使用
lxml
做到这一点?
- Is this possible with
xml.etree
? - How do you do this with
lxml
?
推荐答案
不幸的是,contains()
和 starts-with()
之类的东西不被 xml.etree.ElementTree
内置库.您可以手动检查属性,查找所有 waitingJobs
并使用 .attrib
获取idList
值:
Unfortunately, things like contains()
and starts-with()
are not supported by xml.etree.ElementTree
built-in library. You can manually check the attribute, finding all waitingJobs
and using .attrib
to get to the idList
value:
import xml.etree.ElementTree as ET
data = """<jobs>
<waitingJobs idList="J03ac2db8 J03ac2fb0"/>
</jobs>
"""
root = ET.fromstring(data)
value = 'J03ac2db8'
print([elm for elm in root.findall(".//waitingJobs[@idList]")
if value in elm.attrib["idList"]])
通过lxml.etree
,你可以使用xpath()
方法和contains()
函数:
With lxml.etree
, you can use xpath()
method and contains()
function:
import lxml.etree as ET
data = """<jobs>
<waitingJobs idList="J03ac2db8 J03ac2fb0"/>
</jobs>
"""
root = ET.fromstring(data)
value = 'J03ac2db8'
print(root.xpath(".//waitingJobs[contains(@idList, '%s')]" % value))
这篇关于python xml - 使用正则表达式搜索属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!