简体   繁体   English

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

[英]xml.etree.ElementTree search tag by variable

I have a problem with the xml.etree.ElementTree Module in Python.我对 Python 中的 xml.etree.ElementTree 模块有疑问。 I tried to search for a tag in the XML Tree using a variable:我尝试使用变量在 XML 树中搜索标签:

i = "Http_Https"
print(xmldoc_ports.findall(".//*application-set/[name=i]/application/"))

But it looks like that it did not resolve the variable i .但看起来它没有解析变量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")

Is it possible to use a variable in the findall function?是否可以在 findall 函数中使用变量?

The .//*application-set/[name=i]/application/ is not valid. .//*application-set/[name=i]/application/无效。 I think you meant:我想你的意思是:

xpath = ".//application-set[@name='%s']/application" % i
print(xmldoc_ports.findall(xpath))

Note that @ before the name - this is how you show access the name attribute.请注意名称前的@ - 这是您显示访问name属性的方式。 Also, I've removed the / after the application-set and * before it.另外,我在application-set之后删除了/ ,在它之前删除了*

Also, in order to have variable i inside the XPath, you should/can use string formatting.此外,为了在 XPath 中包含变量i ,您应该/可以使用字符串格式。 The %s is a placeholder for % operator to fill. %s%运算符要填充的占位符。

就像附录一样:如果要替换多个变量,请将它们括在()括号中,并用逗号分隔:

x = document.findall("".//application-set[@name='%s']/application[@method='%s']" % (i, j)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM