[英]xml.etree.ElementTree search tag by variable
我对 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 函数中使用变量?
.//*application-set/[name=i]/application/
无效。 我想你的意思是:
xpath = ".//application-set[@name='%s']/application" % i
print(xmldoc_ports.findall(xpath))
请注意名称前的@
- 这是您显示访问name
属性的方式。 另外,我在application-set
之后删除了/
,在它之前删除了*
。
此外,为了在 XPath 中包含变量i
,您应该/可以使用字符串格式。 %s
是%
运算符要填充的占位符。
就像附录一样:如果要替换多个变量,请将它们括在()
括号中,并用逗号分隔:
x = document.findall("".//application-set[@name='%s']/application[@method='%s']" % (i, j)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.