Devanshu Misra
Devanshu Misra

Reputation: 813

Unable to locate element based on absolute path in XML using Python

My XML file looks something like this:

<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>

Now when I try to find the REF element of the first element using an absolute path where I know the LAUNCH_DATETIME it gives me an error saying invalid predicate. Here is my code:

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)

Here is the following traceback call:

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

When I use the same absolute path on an online xpath evaluator, it gives me the desired output. But when I try the same in my code, it fails. If anyone could tell what the problem is and how it can be resolved, would be great.

Thanks in advance.

Upvotes: 1

Views: 476

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52858

ElementTree's xpath support is limited. Instead of trying to go back up the tree with .. in a predicate on REF, add the predicate to SCAN.

Example...

path = './/SCAN[LAUNCH_DATETIME="2018-05-19T11:05:08Z"]/REF'

Upvotes: 1

Related Questions