簡體   English   中英

將python xml項輸出與list進行比較

[英]Compare python xml item output to list

我是python的新手。 我目前正在做一個小項目,並且在此結構中有一個XML文檔。

<commands>
 <level1 name="sh">show></level1>
  <level2 name="ip">ip</level2>
   <level3 name="int">interface</level3>
    <level4 name="br">show ip interface brief</level4>
 <level1 name="int>interface</level1>
</commands>

我需要做的是從所有元素中提取屬性值,並將它們與列表進行比較。

for in i tree.iter():
 attrib = i.items()
 x = ['name', 'sh']
 if attrib.index(0) in x
   print "BLa"

我的問題是我收到一條錯誤消息,提示“ ValueError:0不在列表中”。 我嘗試了很多不同的方法來查看它是否類似於列表,但事實並非如此。 奇怪的是,當我打印“ attrib”時,我看到一個列表。

直接來自xml.etree.ElemenTree.items()的文檔2.7.3(我的版本)-“ items()以(名稱,值)對的序列形式返回元素屬性。這些屬性以任意順序返回。

請幫助我,請詢問其他信息。

編輯:澄清一下,我想對每個元素值匹配一個說x = ['sh',ip,'int','br']的列表,直到匹配每個列表索引,並且您得到一個最終的elementtext,上面寫着“ show ip界面簡介“

好的,我看到iter()是遞歸的:

dicts = []
for node in root.iter():
    if node.tag == 'level1':
        dicts.append({}) # create new dict for tag chain
    if dicts and 'name' in node.attrib.keys():
        dicts[-1][node.attrib['name']] = node.text.rstrip().split() # list of words

字典的輸出:

{'sh': ['show'], 'br': ['show', 'ip', 'interface', 'brief'], 'ip': ['ip'], 'int': ['interface']}
{'int': ['interface']}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM