2016-10-07 17 views
0

Pythonでxml.etree.ElementTreeモジュールに問題があります。xml.etree.ElementTree検索タグby変数

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

しかし、それは変数iが解決しなかったように見えます:私は、変数を使用してXMLツリー内のタグを検索してみました。

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*の後に/を削除しました。

また、変数iをXPath内に入れるには、文字列の書式設定を使用する必要があります。 %sは、%オペレータが入力するプレースホルダです。

+0

それはそれです。どうもありがとう。 – user159137