Frank Frank - 3 months ago 25
Python Question

Saving List of Tuples in XML

I have a list of lists as such:

[[value A, Value B, Value C], [value D, value E, Value F]]


I've got XML structure as follows:

<root>
<data>
</data>
</root>


I'm trying to understand the best way to write the list into XML.

I understand how to parse the XML, how to get the data, as well as how to write the data to the XML, using etree in my particular case. What I'm struggling with is a conceptual best-practice for storing this data-type in XML.

I apologize for the vauge-nature of this question, but I'm struggling with fundamentals here.

I have tried saving the entire list as a string, which saves fineā€”but it's messy to deal with later on.

UPDATED:

using @mkHun 's general approach, with @Jon Clements attribute concept, the following works for my purposes:

from lxml import etree

var = [["value A", "Value B", "Value C"], ["value D", "value E", "Value F"]]
for j in var:
root = etree.Element('root')
member = etree.SubElement(root, "member")
member.attrib['att1'] = j[0]
member.attrib['att2'] = j[1]
member.attrib['att3'] = j[2]
root.append(member)

out = etree.tostring(root, pretty_print=True)
print(out)


This approach, lessening the iterative depth to consolidate each list into a single
SubElement
, creates an XML structure similar to the following:

<root>
<member att1="Value A" att2="Value B" att3="Value C"/"
<member att1="Value D" att2="Value E" att3="Value F"/"
</root>


I am uncertain that this is the best, or most-efficient manner in which to store this data still, but for now it is the best method which I have tried.

Thanks

Answer

use lxml

from lxml import etree

var = [["value A", "Value B", "Value C"], ["value D", "value E", "Value F"]]
for j in var:
    root = etree.Element('root')
    for m in j:
        data = etree.Element('data')
        data.text = m
        root.append(data)

    out = etree.tostring(root, pretty_print=True)
    print out