web-dev-qa-db-ja.com

Python-ElementTree-要素に絶対パスを使用できません

以下のコードを実行しようとすると、ElementTreeでこのエラーが発生します。

SyntaxError: cannot use absolute path on element

私のXMLドキュメントは次のようになります。

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

コード:

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

MacではPython 2.6を使用しています。Xpath構文を間違って使用していますか?

基本的に、特定のテキストを含むStepText要素が含まれている場合は、すべてのScript要素のname属性を表示したいと思います。

27
Greg

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