Python - ElementTree- cannot use absolute path on element

青春壹個敷衍的年華 提交于 2020-05-10 03:41:47

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/5501118/python-elementtree-cannot-use-absolute-path-on-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!