Python-Liste nach XML und umgekehrt
Ich habe einen Python-Code, den ich geschrieben habe, um eine Python-Liste in ein XML-Element zu konvertieren. Es ist für die Interaktion mit LabVIEW gedacht, daher das seltsame XML-Array-Format. Wie auch immer, hier ist der 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
Jetzt muss ich eine unpack () -Methode schreiben, um das gepackte XML-Array wieder in eine Python-Liste zu konvertieren. Ich kann die Array-Dimensionen und Daten gut extrahieren:
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?
Ich bin mir aber nicht sicher, wie ich das Array abflachen soll. Was wäre ein effizienter Weg, um das zu tun?
Bearbeiten: So sieht die Python-Liste und das zugehörige XML aus. Hinweis: Die Arrays sind n-dimensional.
data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
Und dann die XML-Version:
<Array>
<Dimsize>2</Dimsize>
<Dimsize>2</Dimsize>
<Dimsize>2</Dimsize>
<I32>
<Name />
<Val>1</Val>
</I32>
... 2, 3, 4, etc.
</Array>
Das tatsächliche Format ist jedoch nicht wichtig, ich weiß nur nicht, wie ich die Liste reduzieren soll:
data = [1, 2, 3, 4, 5, 6, 7, 8]
zurück in:
data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
gegeben:
lengths = [2, 2, 2]
Angenommen, pack_simple () und unpack_simple () machen dasselbe wie pack () und unpack () für die Basisdatentypen (int, long, string, boolean).