I am farely new at python. I am currently working on a little project and I have a XML document in this structure.
<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>
What I need to do is to extract the attribute values from all elements and compare them to a list.
for in i tree.iter():
attrib = i.items()
x = ['name', 'sh']
if attrib.index(0) in x
print "BLa"
My problem is that I get a error that says "ValueError: 0 is not in list". I have tried much different things to see if it acts like a list but it doesn't. Strangely enough when I print 'attrib' I see a list.
Directly from doc 2.7.3(My version) of xml.etree.ElemenTree.items() - "items() Returns the element attributes as a sequence of (name, value) pairs. The attributes are returned in an arbitrary order.
Please help me and please ask for any other information.
Edit: To clarify I want to match a list say x = ['sh',ip,'int','br'] to every element value until every list index is matched and you come to a final elementtext which says "show ip interface brief"
OK, I see iter() is recursive:
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
Output for dicts:
{'sh': ['show'], 'br': ['show', 'ip', 'interface', 'brief'], 'ip': ['ip'], 'int': ['interface']}
{'int': ['interface']}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.