xml.etree.ElementTree按变量搜索标签

时间:2016-10-07 14:50:08

标签: python xml-parsing

我在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函数中使用变量?

1 个答案:

答案 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%运算符填充的占位符。