使用 Python 和 ElementTree 在 XML 中搜索变量属性
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: invalid predicate
这是 ElementTree
的限制吗?我应该使用其他东西吗?
"SyntaxError: invalid predicate"
file[@id=fileid]
是无效的 XPath 表达式,因为您错过了属性值两边的引号。如果将引号放在 fileid
周围:file[@id="fileid"]
表达式将变为有效,但它不会找到任何内容,因为它会搜索 file
元素 id
等于到 "fileid" 字符串.
使用字符串格式化将fileid
值插入到XPath表达式中:
root.find('file[@id="{value}"]'.format(value=fileid))
我有一个 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: invalid predicate
这是 ElementTree
的限制吗?我应该使用其他东西吗?
"SyntaxError: invalid predicate"
file[@id=fileid]
是无效的 XPath 表达式,因为您错过了属性值两边的引号。如果将引号放在 fileid
周围:file[@id="fileid"]
表达式将变为有效,但它不会找到任何内容,因为它会搜索 file
元素 id
等于到 "fileid" 字符串.
使用字符串格式化将fileid
值插入到XPath表达式中:
root.find('file[@id="{value}"]'.format(value=fileid))