title: Python list to XML and vice versa
body: <p>I have some python code that I wrote to convert a python list into an XML element. It's meant for interacting with LabVIEW, hence the weird XML array format. Anyways, here's the code:</p>
  
  <pre><code>def pack(data):
    # create the result element
    result = xml.Element("Array")
  
    # report the dimensions
    ref = data
    while isinstance(ref, list):
      xml.SubElement(result, "Dimsize").text = str(len(ref))
      ref = ref[0]
  
    # flatten the data
    while isinstance(data[0], list):
      data = sum(data, [])
  
    # pack the data
    for d in data:
      result.append(pack_simple(d))
  
    # return the result
    return result
  </code></pre>
  
  <p>Now I need to write an unpack() method to convert the packed XML Array back into a python list. I can extract the array dimensions and data just fine:</p>
  
  <pre><code>def unpack(element):
    # retrieve the array dimensions and data
    lengths = []
    data = []
    for entry in element:
      if entry.text == "Dimsize":
        lengths.append(int(entry.text))
  
      else:
        data.append(unpack_simple(entry))
  
    # now what?
  </code></pre>
  
  <p>But I am not sure how to unflatten the array. What would be an efficient way to do that?</p>
  
  <p>Edit: Here's what the python list and corresponding XML looks like. Note: the arrays are n-dimensional.</p>
  
  <pre><code>data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
  </code></pre>
  
  <p>And then the XML version:</p>
  
  <pre><code>&lt;Array&gt;
    &lt;Dimsize&gt;2&lt;/Dimsize&gt;
    &lt;Dimsize&gt;2&lt;/Dimsize&gt;
    &lt;Dimsize&gt;2&lt;/Dimsize&gt;
    &lt;I32&gt;
      &lt;Name /&gt;
      &lt;Val&gt;1&lt;/Val&gt;
    &lt;/I32&gt;
  
    ... 2, 3, 4, etc.
  &lt;/Array&gt;
  </code></pre>
  
  <p>The actual format isn't important though, I just don't know how to unflatten the list from:</p>
  
  <pre><code>data = [1, 2, 3, 4, 5, 6, 7, 8]
  </code></pre>
  
  <p>back into:</p>
  
  <pre><code>data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
  </code></pre>
  
  <p>given:</p>
  
  <pre><code>lengths = [2, 2, 2]
  </code></pre>
  
  <p>Assume pack_simple() and unpack_simple() do the same as pack() and unpack() for the basic data types (int, long, string, boolean).</p>