当我尝试运行下面的代码时,我在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元素。
发布于 2011-03-31 22:27:51
原来我需要说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
https://stackoverflow.com/questions/5501118
复制相似问题