38

I'm getting this error in ElementTree when I try to run the code below:

SyntaxError: cannot use absolute path on element

My XML document looks like this:

<Scripts>
  <Script>
    <StepList>
      <Step>
        <StepText>
        </StepText>
        <StepText>
        </StepText>
      </Step>
    </StepList>
  </Script>
</Scripts>

Code:

import xml.etree.ElementTree as ET

def search():
    root = ET.parse(INPUT_FILE_PATH)
    for target in root.findall("//Script"):
        print target.attrib['name']
        print target.findall("//StepText")

I'm on Python 2.6 on Mac. Am I using Xpath syntax wrong?

Basically I want to show every Script elements name attribute if it contains a StepText element with certain text.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Greg
  • 45,306
  • 89
  • 231
  • 297
  • ElementTree seems a naff implementation. It should allow absolute paths like //SOURCE/text() – JGFMK Nov 14 '22 at 11:26

1 Answers1

57

Turns out I needed to say target.findall(".//StepText"). I guess anything without the '.' is considered an absolute path?

Updated working code:

def search():
    root = ET.parse(INPUT_FILE_PATH)
    for target in root.findall("//Script"):
        stepTexts = target.findall(".//StepText")
        for stepText in stepTexts:
            if FIND.lower() in stepText.text.lower():
                print target.attrib['name'],' -- ',stepText.text
Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
Greg
  • 45,306
  • 89
  • 231
  • 297
  • 8
    Any XPath expression starting with `/` or `//` operator is an absolute expression. Besides this, that restriction (absolute expressions not allowed with other context node than root) is specific to your XPath engine implementation. –  Mar 31 '11 at 16:07
  • @user357812 is there a way to query which engine a particular XPath implementation is using? – jxramos Feb 22 '17 at 19:27