Python-ElementTree-无法在元素上使用绝对路径 [英] Python - ElementTree- cannot use absolute path on element
本文介绍了Python-ElementTree-无法在元素上使用绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试运行以下代码时,我在ElementTree中收到此错误:
I'm getting this error in ElementTree when I try to run the code below:
SyntaxError: cannot use absolute path on element
我的XML文档如下所示:
My XML document looks like this:
<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语法错误吗?
I'm on Python 2.6 on Mac. Am I using Xpath syntax wrong?
基本上,我想显示每个Script元素名称属性,如果它包含带有特定文本的StepText元素。
Basically I want to show every Script elements name attribute if it contains a StepText element with certain text.
推荐答案
结果我需要说 target.findall( .// StepText)
。我猜没有'。'的东西都被认为是绝对路径吗?
Turns out I needed to say target.findall(".//StepText")
. I guess anything without the '.' is considered an absolute path?
更新后的工作代码:
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
这篇关于Python-ElementTree-无法在元素上使用绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文