简体   繁体   English

Python-在TreeView结构上显示XML文件

[英]Python - show an XML file on a TreeView structure

I have this code that tranverse a dict object and put it on a TreeView. 我有遍历dict对象并将其放在TreeView上的这段代码。 For simple xml it gets ok but with complex xml it doesn't work. 对于简单的xml来说可以,但是对于复杂的xml则不起作用。

The problem is with the walk_dict function, but I can't get it right. 问题出在walk_dict函数上,但是我做错了。

#-*- encoding: utf8 -*-
from Tkinter import *
from ttk import Treeview
import xmltodict

class App:

  def __init__(self, root):

    try:
      self.tagsoup = xmltodict.parse(file(sys.argv[1],'r').read())
      self.tree = Treeview(root, height=30)
      self.tree.pack()
      self.last = ''
      self.walk_dict(self.tagsoup)
    except Exception as e:
      print e

  def walk_dict(self, d,depth=0):
    for k,v in sorted(d.items(),key=lambda x: x[0]):
      if isinstance(v, dict):
        self.last = k
        self.tree.insert('', 'end', k, text = k)
        self.walk_dict(v,depth+1)
      else:
        self.tree.insert(self.last, 'end', k, text = k)
        self.tree.insert(k, 'end', v, text = v)

root = Tk()
App(root)
root.mainloop()

The xml I am feeding is this: 我提供的xml是这样的:

<menu>
    <opcao1>Aspargos</opcao1>
    <opcao2>Tomate frito</opcao2>
    <opcao3>Abóbora caramelizada</opcao3>
    <opcao4>Churrasco de ovelha</opcao4>
    <opcao5>Pizza</opcao5>
    <opcao6>
        <lol>Copter</lol>
        <meh>lolcopter</meh>
        <bla>
            <woo>foo</woo>
        </bla>
    </opcao6>
</menu>

这是输出 This is the output. 这是输出。 Note that opcao6 is rendered out of the tree, and its children are rendered below. 请注意,opcao6是在树外渲染的,其子级在下面渲染。

The problem is that no matter how deep your recursion, you're always creating items as children of the root item. 问题在于,无论递归有多深,您都始终将项创建为根项的子项。 Instead, you need to save the id of the new item, and pass that in as a new parent when you make a nested call to walk_dict . 相反,您需要保存新项目的ID,并在对walk_dict进行嵌套调用时将其作为新的父项传递。

It would look something like this: 它看起来像这样:

def walk_dict(self, d,depth=0, parent=""):
  for k,v in sorted(d.items(),key=lambda x: x[0]):
    item = self.tree.insert(parent, 'end', k, text = k)
    if isinstance(v, dict):
      self.walk_dict(v,depth+1, parent=item)
    else:
      self.tree.insert(item, 'end', v, text = v)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM