[英]Search XML for Variable Attribute Using Python & ElementTree
我有一个看起来像这样的XML(简化):
<file id="file-10">
<clip>1</clip>
<timecode>1:00:00:00</timecode>
</file>
<file id="file-11">
<clip>2</clip>
<timecode>2:00:00:00</timecode>
</file>
我正在尝试使用ElementTree搜索具有特定id属性的文件元素。 这有效:
correctfile = root.find('file[@id="file-10"]')
这不是:
fileid = 'file-10'
correctfile = root.find('file[@id=fileid]')
我得到:
SyntaxError:谓词无效
这是ElementTree
的限制吗? 我应该使用其他东西吗?
“ SyntaxError:无效谓词”
file[@id=fileid]
是无效的XPath表达式,因为您错过了属性值周围的引号。 如果将引号引起来, fileid
: file[@id="fileid"]
将变为有效,但它将找不到任何东西,因为它将搜索id
等于“ fileid” string的file
元素。
使用字符串格式将fileid
值插入XPath表达式中:
root.find('file[@id="{value}"]'.format(value=fileid))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.