我的python函数获取元素的属性值
import lxml.etree as ET
def xml_get_attrib_value(filepath, xpath, attribute):
it = ET.iterparse(filepath)
for _, el in it:
_, _, el.tag = el.tag.rpartition('}')
root = it.root
element = root.find(xpath)
value = element.attrib[attribute]
return value
XML 片段:
<outboundRelationship typeCode="SPRT">
<priorityNumber value="1" />
<relatedInvestigation classCode="INVSTG" moodCode="EVN">
<code code="2" codeSystem="2.16.840.1.113883.3.989.2.1.1.22" codeSystemVersion="2.0" />
我想获取属性的值,“value”在
如果我发送一个简单的 xpath,它就可以工作。
xpath:
.//outboundRelationship[@typeCode='SPRT']/priorityNumber
但是,如果我想检查 PriorityNumber 的属性,条件是它应该是“latedInvestigation”的同级,而“latedInvestigation”又具有一个具有特定属性的子节点“code”。我收到错误‘
SyntaxError: invalid predicate
’
x路径:
.//outboundRelationship[@typeCode='SPRT'][relatedInvestigation/code[@code='2'][@codeSystem='2.16.840.1.113883.3.989.2.1.1.22']]/priorityNumber
我尝试在 xpath 中使用 previous:sibling 但这也不起作用。
如何发送这样的xpath?还有其他方法可以做到这一点吗?
使用
xpath()
代替 find
from lxml import etree
xtree = etree.parse('tmp.xml')
p = xtree.xpath(".//outboundRelationship[@typeCode='SPRT'][relatedInvestigation/code[@code='2'][@codeSystem='2.16.840.1.113883.3.989.2.1.1.22']]/priorityNumber")
print(p[0].attrib['value'])
结果
'1'
lxml 版本
etree.__version__
'4.9.3'