Python - show an XML file on a TreeView structure -


i have code tranverse dict object , put on treeview. simple xml gets ok complex xml doesn't work.

the problem walk_dict function, can't right.

#-*- encoding: utf8 -*- tkinter import * 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 e:       print e    def walk_dict(self, d,depth=0):     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 feeding this:

<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 output output. note opcao6 rendered out of tree, , children rendered below.

the problem no matter how deep recursion, you're creating items children of root item. instead, need save id of new item, , pass in new parent when make nested call walk_dict.

it this:

def walk_dict(self, d,depth=0, parent=""):   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) 

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -