我的XML文件看起来像这样:
<SCAN_LIST_OUTPUT>
<RESPONSE>
<DATETIME>2018-05-21T11:29:05Z</DATETIME>
<SCAN_LIST>
<SCAN>
<REF>scan/1526727908.25005</REF>
<TITLE><![CDATA[ACRS_Scan]]></TITLE>
<LAUNCH_DATETIME>2018-05-19T11:05:08Z</LAUNCH_DATETIME>
</SCAN>
<SCAN>
<REF>scan/1526549903.07613</REF>
<TITLE><![CDATA[testScan]]></TITLE>
<LAUNCH_DATETIME>2018-05-17T09:38:23Z</LAUNCH_DATETIME>
</SCAN>
</SCAN_LIST>
</RESPONSE>
</SCAN_LIST_OUTPUT>
现在,当我尝试使用绝对路径找到第一个元素的REF元素时,我知道LAUNCH_DATETIME,它给出了一个错误,指出无效谓词。 这是我的代码:
import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(response))
groot = tree.getroot()
path = './/REF[../LAUNCH_DATETIME="2018-05-19T11:05:08Z"]'
scan_id = tree.find(path)
以下是回溯调用:
KeyError: ('.//REF[../LAUNCH_DATETIME="2018-05-19T11:05:08Z"]', None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/doomsday/PycharmProjects/untitled/venv/ScanList.py", line 44, in <module>
scan_id = tree.find(path)
File "/usr/lib/python3.5/xml/etree/ElementTree.py", line 651, in find
return self._root.find(path, namespaces)
File "/usr/lib/python3.5/xml/etree/ElementPath.py", line 298, in find
return next(iterfind(elem, path, namespaces), None)
File "/usr/lib/python3.5/xml/etree/ElementPath.py", line 277, in iterfind
selector.append(ops[token[0]](next, token))
File "/usr/lib/python3.5/xml/etree/ElementPath.py", line 233, in prepare_predicate
raise SyntaxError("invalid predicate")
SyntaxError: invalid predicate
当我在在线xpath评估器上使用相同的绝对路径时,它会为我提供所需的输出。但是当我在我的代码中尝试相同时,它失败了。如果有人能分辨出问题是什么以及如何解决问题,那就太好了。
提前致谢。
答案 0 :(得分:1)
ElementTree的xpath support是有限的。不要尝试在..
的谓词中使用REF
返回树,而是将谓词添加到SCAN
。
示例...
path = './/SCAN[LAUNCH_DATETIME="2018-05-19T11:05:08Z"]/REF'