Python-Ref > GUI programming with PyGTK > Data structures > TreeStore for XML
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce
GTK Widgety

TreeStore for XML

How to create a TreeStore that describes the strucure of an XML document.
The structure of an XML dpocument forms a natural tree-like structure. The only thing we need to do to put this structure into a TreeStore is a bit of recursive magic.
Expand/Shrink
<examples>
  <example num="1">
    <title>Example 1</title>
    <text>This is example nr. 1. It shows how an example looks.</text>
  </example>

  <example num="2">
    <title>Example 2</title>
    <text>Another example. Imagine some ingenious text here...</text>
  </example>
</examples>
  1   import gtk
  2   import xml.dom.minidom as dom
  3   
  4   def add_element_to_treestore( e, parent, store):
  5     if isinstance( e, dom.Element):
  6       me = store.append( parent, [e.nodeName])
  7       for ch in e.childNodes:
  8         add_element_to_treestore( ch, me, store)
  9   
 10   # table with 1 string column
 11   store = gtk.TreeStore( str)
 12   doc = dom.parse( "example.xml")
 13   add_element_to_treestore( doc.childNodes[0], None, store)
 14     
 15   # iterate over the store
 16   for row in store:
 17     print row[0]
 18     for child in row.iterchildren():
 19       print " ", child[0]
 20       for grandchild in child.iterchildren():
 21         print "   ", grandchild[0]
stdout:
examples
  example
    title
    text
  example
    title
    text
Doba běhu: 109.3 ms