如題,在用python決議xml檔案時需要根據不同欄位查詢與之對應的內容,需要把傳入的欄位存到變數中,然后查符合
例如:
(1)傳入內容為“test”
(2)將“test”賦值給變數
a=“test”
(3)將a放到謂語中,借助其做一些條件過濾,但會報錯
root.findall('.//service-identification/header-rule[name=a]')
該問題如何解決,或者還有沒有其他思路解決(只了解python,希望能在此語言中找到解決辦法)。
由于剛入門,現想到的辦法是做大量的if判斷,但是這種辦法太復雜,太low了。。。。
uj5u.com熱心網友回復:
字串拼接就可以啊uj5u.com熱心網友回復:
隨著程式的運行,傳入的字串(”test“)會變,所以不能直接接上”test“字串。uj5u.com熱心網友回復:
root.findall('.//service-identification/header-rule[name={}]'.format(a))uj5u.com熱心網友回復:
root.findall('.//service-identification/header-rule[name={}]'.format(a))驗證不行。。。。。。
In [19]: root.findall('.//service-identification/header-rule[name={}]'.format(a))
Traceback (most recent call last):
File "c:\users\eshicyu\appdata\local\programs\python\python38\lib\site-packages\IPython\core\interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-19-95b1ceaaf61a>", line 1, in <module>
root.findall('.//service-identification/header-rule[name={}]'.format(a))
File "src\lxml\etree.pyx", line 1558, in lxml.etree._Element.findall
File "src\lxml\_elementpath.py", line 334, in lxml._elementpath.findall
File "src\lxml\_elementpath.py", line 312, in lxml._elementpath.iterfind
File "src\lxml\_elementpath.py", line 295, in lxml._elementpath._build_path_iterator
File "src\lxml\_elementpath.py", line 237, in lxml._elementpath.prepare_predicate
File "<string>", line unknown
SyntaxError: invalid predicate
In [20]: a
Out[20]: 'NoProxy_12530_01_hr_ip'
——————————————————————————————————————————————
In [21]: root.findall('.//service-identification/header-rule[name="NoProxy_12530_0
...: 1_hr_ip"]')
Out[21]: [<Element header-rule at 0x207a4925bc0>]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/82732.html
上一篇:怎樣安裝requests?求解
