2016-04-14 73 views
1

我是很新的XML使用Python和我有以下XML字符串,我得到的是來自網絡設備的響應:從一個節點遍歷XML到另一個使用Python

'<Response MajorVersion="1" MinorVersion="0"><Get><Configuration><OSPF MajorVersion="19" MinorVersion="2"><ProcessTable><Process><Naming><ProcessName>1</ProcessName></Naming><DefaultVRF><AreaTable><Area><Naming><AreaID>0</AreaID></Naming><Running>true</Running><NameScopeTable><NameScope><Naming><InterfaceName>Loopback0</InterfaceName></Naming><Running>true</Running><Cost>1000</Cost></NameScope><NameScope><Naming><InterfaceName>Loopback1</InterfaceName></Naming><Running>true</Running><Cost>1</Cost></NameScope><NameScope><Naming><InterfaceName>GigabitEthernet0/0/0/0</InterfaceName></Naming><Running>true</Running><Cost>1</Cost></NameScope></NameScopeTable></Area></AreaTable></DefaultVRF><Start>true</Start></Process></ProcessTable></OSPF></Configuration></Get><ResultSummary ErrorCount="0" /></Response>' 

我有以下代碼來檢索接口信息以及與之相關的接口成本。不過,我還想獲得與每個界面相關的'AreaID'標籤作爲我的詞典的一部分。無法正常瀏覽樹檢索areaID表示標記值:

for node in x.iter('NameScope'): 
int_name = str(node.find('Naming/InterfaceName').text) 
d[int_name] = {} 
d[int_name]['cost'] = str(node.find('Cost').text) 

此代碼「d」時,給出了下面的輸出打印:

{'GigabitEthernet0/0/0/0': {'cost': '1'}, 
'Loopback0': {'cost': '1000'}, 
'Loopback1': {'cost': '1'}} 

我想是這樣的輸出:

{'GigabitEthernet0/0/0/0': {'cost': '1', 'area': 0}, 
'Loopback0': {'cost': '1000', 'area': 0}, 
'Loopback1': {'cost': '1', 'area': 0}} 

任何建議或修改我的代碼將非常感激!

回答

1

我會用preceding符號:

node.xpath(".//preceding::AreaID")[0].text 

完整代碼,我執行:

from lxml import etree as ET 

x = ET.parse("input.xml") 
d = {} 
for node in x.iter('NameScope'): 
    int_name = str(node.find('Naming/InterfaceName').text) 
    d[int_name] = { 
     'cost': str(node.find('Cost').text), 
     'area': node.xpath(".//preceding::AreaID")[0].text 
    } 

print(d) 

打印:

{ 
    'Loopback0': {'cost': '1000', 'area': '0'}, 
    'Loopback1': {'cost': '1', 'area': '0'}, 
    'GigabitEthernet0/0/0/0': {'cost': '1', 'area': '0'} 
} 
+0

感謝您的答覆。但是,'x'是一個xml.etree.ElementTree.Element對象。因此,節點不具有xpath屬性。我在Python 2.7。此外,我嘗試了你的建議,做到這一點:「area = str(node.find(」.//前置:: AreaID「)[0] .text)」,我得到了這個錯誤「SyntaxError:prefix'在'not'在前綴映射中找到 「 – pypep278

+0

另外,我的輸入不是xml文件,而是xml.etree.ElementTree.Element對象。 – pypep278

+1

@ pypep278好吧,即使我定義了一個'data'字符串變量並將'x'定義爲'x = ET.fromstring(data)',它也適用於我。如果使用'xpath()'方法會發生什麼? – alecxe