35

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.

4

1 回答 1

54

原来我需要说target.findall(".//StepText")。我猜没有'。被认为是绝对路径?

更新的工作代码:

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
于 2011-03-31T14:27:50.847 回答