我是python的新手并寫道:
root = ET.fromstring(xml_output)
host = root.find('host')
if host:
ports = host.find('ports')
if ports:
for port in ports:
service = port.find('service')
if service:
print(service.attrib.get('name'))
我的代碼可以找到,但看起來很丑,我該如何解決?寫的太深了看不懂,另外如果我想在name下添加其他欄位怎么辦?那將是糟糕的代碼設計。
uj5u.com熱心網友回復:
我認為對您來說最重要的部分是最后的列印陳述句。如果是這種情況,那么您可以嘗試一下,除了塊。根據您想知道它失敗的地方,您必須使此代碼更詳細一些。
root = ET.fromstring(xml_output)
try:
host = root.find('host')
ports = host.find('ports')
for port in ports:
service = port.find('service')
print(service.attrib.get('name'))
catch:
print("Something did not connect")
uj5u.com熱心網友回復:
嵌套 ifs 的一種替代方法是使用保護子句:
root = ET.fromstring(xml_output)
host = root.find('host')
if not host:
return
ports = host.find('ports')
if not ports:
return
for port in ports:
service = port.find('service')
if not service:
continue
print(service.attrib.get('name'))
此外,在您的情況下,如果埠為空或 None 它不會回圈通過埠,因此:
if ports:
for port in ports:
service = port.find('service')
if service:
print(service.attrib.get('name'))
只是:
for port in ports:
service = port.find('service')
if service:
print(service.attrib.get('name'))
就足夠了。
uj5u.com熱心網友回復:
由于您真正要做的是列印節點下節點下name所有service節點的屬性,因此您可以通過呼叫具有適當 XPath 運算式的方法來找到所述節點:portshostiterfind
for service in ET.fromstring(xml_output).iterfind('.//host//ports//service'):
print(service.attrib.get('name'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346312.html
下一篇:如何根據多個變數制作條件變數?
