2016-10-07 92 views
0

我在Python中遇到了xml.etree.ElementTree模塊的問題。我試圖尋找使用變量在XML樹標籤:xml.etree.ElementTree變量搜索標記

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

.//*application-set/[name=i]/application/無效。我想你的意思是:

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

注意@名稱前 - 這是你如何證明訪問name屬性。另外,我在application-set*之前刪除了/

此外,爲了在XPath中有變量i,您應該/可以使用字符串格式。 %s%運算符的佔位符。

+0

就是這樣。非常感謝。 – user159137