我在Python中使用xml.etree.ElementTree模块时遇到问题。我尝试使用变量在XML树中搜索标记:
i = "Http_Https"
print(xmldoc_ports.findall(".//*application-set/[name=i]/application/"))
但看起来它没有解析变量i
。
Traceback (most recent call last):
File "test.py", line 223, in <module>
print(xmldoc_ports.findall(".//*application-set/[name=i]/application/"))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 749, in findall
return self._root.findall(path, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 390, in findall
return ElementPath.findall(self, path, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 293, in findall
return list(iterfind(elem, path, namespaces))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 263, in iterfind
selector.append(ops[token[0]](next, token))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 224, in prepare_predicate
raise SyntaxError("invalid predicate")
是否可以在findall函数中使用变量?
答案 0 :(得分:1)
.//*application-set/[name=i]/application/
无效。我想你的意思是:
xpath = ".//application-set[@name='%s']/application" % i
print(xmldoc_ports.findall(xpath))
请注意名称前的@
- 这是您显示name
属性的访问权限的方式。另外,我在/
和application-set
之前删除了*
。
此外,为了在XPath中包含变量i
,您应该/可以使用字符串格式。 %s
是%
运算符填充的占位符。