Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let's assume that you know how to create XML.</p> <p>Let's assume that 'level' in your data increases if the data is nested in the previous node, and it only increases by 1. If the level decreases, this means that you are not talking about current node any more, but rather about some node above; level == 1 means 'attach at document level'.</p> <ul> <li><p>To handle <em>increasing</em> levels, you just need to track the previous node. If the level increases by one, you create a new node and make it a child of previous node.</p></li> <li><p>To handle <em>the same</em> level, you need to remember the parent of the previously created node. You attach the new node to that parent, because it's a peer of the previous node.</p></li> <li><p>To handle <em>decreasing</em> levels, you need to step back from previous node several steps so that you're on the right level. Can you see a pattern?</p></li> </ul> <p>Really you need to remember the whole chain from document level to the previously created node. If <code>next_node.level == previous_node.level + 1</code>, you attach it to the end of chain. Else you step back <code>previous_node.level - next_node.level + 1</code> items up the chain and use that node as the parent. We assume that level 0 is document level.</p> <p>A bit of code to illustrate this:</p> <pre><code>def nest(input): ret = {'level': 0} # 'document level' path = [ret] for item in input: node = dict(item) # a copy of item, lest we alter input old_level = path[-1]['level'] # last element's new_level = node['level'] delta = new_level - old_level - 1 if delta &lt; 0: path = path[:delta] children_list = path[-1].get('_children', None) or [] children_list.append(node) path[-1]['_children'] = children_list path.append(node) return ret from pprint import PrettyPrinter pr = PrettyPrint(indent=2).pprint pr(nest(toc)) </code></pre> <p>and you see</p> <pre><code>{ '_children': [ { '_children': [ { 'entryno': 2, 'level': 2, 'pageno': 19, 'title': 'title b'}], 'entryno': 1, 'level': 1, 'pageno': 17, 'title': 'title a'}, { 'entryno': 3, 'level': 1, 'pageno': 25, 'title': 'title c'}], 'level': 0} </code></pre> <p>Under <code>_children</code> we list nested nodes.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload