[英]Compare python xml item output to list
I am farely new at python. 我是python的新手。 I am currently working on a little project and I have a XML document in this structure.
我目前正在做一个小项目,并且在此结构中有一个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>
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". 我的问题是我收到一条错误消息,提示“ ValueError:0不在列表中”。 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.
奇怪的是,当我打印“ attrib”时,我看到一个列表。
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. 直接来自xml.etree.ElemenTree.items()的文档2.7.3(我的版本)-“ items()以(名称,值)对的序列形式返回元素属性。这些属性以任意顺序返回。
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" 编辑:澄清一下,我想对每个元素值匹配一个说x = ['sh',ip,'int','br']的列表,直到匹配每个列表索引,并且您得到一个最终的elementtext,上面写着“ show ip界面简介“
OK, I see iter() is recursive: 好的,我看到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
Output for dicts: 字典的输出:
{'sh': ['show'], 'br': ['show', 'ip', 'interface', 'brief'], 'ip': ['ip'], 'int': ['interface']}
{'int': ['interface']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.