【问题标题】:Compare python xml item output to list将 python xml 项目输出与列表进行比较
【发布时间】:2015-02-10 21:27:40
【问题描述】:

我对 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 is not in list”。我尝试了很多不同的方法来查看它是否像列表一样,但事实并非如此。奇怪的是,当我打印“attrib”时,我看到了一个列表。

直接来自 xml.etree.ElemenTree.items() 的 doc 2.7.3(我的版本) - “items() 将元素属性作为 (name, value) 对的序列返回。属性以任意顺序返回。

请帮助我,并询问任何其他信息。

编辑:为了澄清我想将一个列表说 x = ['sh',ip,'int','br'] 匹配到每个元素值,直到每个列表索引都匹配并且你来到一个最终的元素文本,它说"显示ip接口简介"

【问题讨论】:

  • 提取xml数据的代码是什么?如果文件中没有更多内容, 应该是根节点。我找不到 items() 是递归的。

标签: python xml elementtree xml.etree


【解决方案1】:

好的,我看到 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

dicts 的输出:

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

【讨论】:

  • 如果层数不应引发堆栈溢出错误,您可以在递归函数中调用 iter(),即
猜你喜欢
  • 2022-11-12
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 2017-01-30
  • 2018-09-10
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
相关资源
最近更新 更多