2009-06-19 22 views
58

C'è un semplice modulo di serializzazione JSON con il nome "simplejson" che serializza facilmente oggetti Python su JSON.Serializza dizionario Python in XML

Sto cercando un modulo simile che può serializzare in XML.

risposta

13
+4

> http://code.activestate.com/recipes/415983/ Questo non viene serializzato in XML solo per il formato di marshalling. E inoltre non mi piace sys.exit su Exception. > http://sourceforge.net/projects/pyxser/ Questo non è BSD. Scusa se ho dimenticato di menzionare, sto cercando il modulo python o BSD, quindi posso distribuirlo con il mio software BSD. Gli ultimi 2 - per i servizi Web, sto cercando un serializator XML regolare. – zinovii

+1

zdmytriv: è possibile distribuire una libreria LGPL con il proprio codice BSD senza responsabilità. – nosklo

+0

@nosklo: non sapevo che puoi farlo. Ora lo so, grazie. – zinovii

17

C'è huTools.structured.dict2xml che cerca di essere compatibile con simplejson nello spirito. Puoi dare suggerimenti su come avvolgere sotto-strutture annidate. Controllare la documentazione per huTools.structured.dict2et che restituisce invece gli oggetti ElementTree se le stringhe sono state restituite da dict2xml.

>>> data = {"kommiauftragsnr":2103839, "anliefertermin":"2009-11-25", "prioritaet": 7, 
... "ort": u"Hücksenwagen", 
... "positionen": [{"menge": 12, "artnr": "14640/XL", "posnr": 1},], 
... "versandeinweisungen": [{"guid": "2103839-XalE", "bezeichner": "avisierung48h", 
...       "anweisung": "48h vor Anlieferung unter 0900-LOGISTIK avisieren"}, 
... ]} 

>>> print ET.tostring(dict2et(data, 'kommiauftrag', 
... listnames={'positionen': 'position', 'versandeinweisungen': 'versandeinweisung'})) 
'''<kommiauftrag> 
<anliefertermin>2009-11-25</anliefertermin> 
<positionen> 
    <position> 
     <posnr>1</posnr> 
     <menge>12</menge> 
     <artnr>14640/XL</artnr> 
    </position> 
</positionen> 
<ort>H&#xC3;&#xBC;cksenwagen</ort> 
<versandeinweisungen> 
    <versandeinweisung> 
     <bezeichner>avisierung48h</bezeichner> 
     <anweisung>48h vor Anlieferung unter 0900-LOGISTIK avisieren</anweisung> 
     <guid>2103839-XalE</guid> 
    </versandeinweisung> 
</versandeinweisungen> 
<prioritaet>7</prioritaet> 
<kommiauftragsnr>2103839</kommiauftragsnr> 
</kommiauftrag>''' 
+0

huTools non è compatibile con Python 3 (l'oggetto '' '' dict 'non ha attributo' iteritems''''). – thomaskonrad

+0

Quali sono i termini di licenza di questa cosa? Posso usarlo la mia app commerciale? –

11

provare questo. unico problema Non faccio uso di attributi (perchè non mi piace loro)
dict2xml on pynuggets.wordpress.com
dict2xml on activestate

from xml.dom.minidom import Document 
import copy 

class dict2xml(object): 
    doc  = Document() 

    def __init__(self, structure): 
     if len(structure) == 1: 
      rootName = str(structure.keys()[0]) 
      self.root = self.doc.createElement(rootName) 

      self.doc.appendChild(self.root) 
      self.build(self.root, structure[rootName]) 

    def build(self, father, structure): 
     if type(structure) == dict: 
      for k in structure: 
       tag = self.doc.createElement(k) 
       father.appendChild(tag) 
       self.build(tag, structure[k]) 

     elif type(structure) == list: 
      grandFather = father.parentNode 
      tagName  = father.tagName 
      grandFather.removeChild(father) 
      for l in structure: 
       tag = self.doc.createElement(tagName) 
       self.build(tag, l) 
       grandFather.appendChild(tag) 

     else: 
      data = str(structure) 
      tag  = self.doc.createTextNode(data) 
      father.appendChild(tag) 

    def display(self): 
     print self.doc.toprettyxml(indent=" ") 

if __name__ == '__main__': 
    example = {'auftrag':{"kommiauftragsnr":2103839, "anliefertermin":"2009-11-25", "prioritaet": 7,"ort": u"Huecksenwagen","positionen": [{"menge": 12, "artnr": "14640/XL", "posnr": 1},],"versandeinweisungen": [{"guid": "2103839-XalE", "bezeichner": "avisierung48h","anweisung": "48h vor Anlieferung unter 0900-LOGISTIK avisieren"},]}} 
    xml = dict2xml(example) 
    xml.display() 
+1

Ecco alcuni problemi con la creazione di un'altra istanza di dict2xml 'xml.dom.HierarchyRequestErr: due elementi del documento non consentiti ', quindi ho aggiunto il metodo unlink: ' def unlink (self): self.doc.unlink() ' –

2

maggior parte degli oggetti in Python sono rappresentati come dicts sotto:

>>> class Fred(object) : 
... def __init__(self, n) : self.n = n 
... 
>>> a = Fred(100) 
>>> print a.__dict__ 
{'n': 100} 

Quindi questo è simile a chiedendo come convertire dicts in XML. ci sono strumenti per la conversione di dict a/da XML a:

http://www.picklingtools.com

Ecco un semplice esempio:

>>> import xmltools 

    >>> d = {'a':1, 'b':2.2, 'c':'three' } 
    >>> xx = xmltools.WriteToXMLString(d) 
    >>> print xx 
    <?xml version="1.0" encoding="UTF-8"?> 
    <top> 
     <a>1</a> 
     <b>2.2</b> 
     <c>three</c> 
    </top> 

C'è molta documentazione sul sito web che mostra esempi:

XML Tools Manual

È difficile convertire "esattamente" tra dicts e XML: cos'è un elenco? Cosa fai con gli attributi? Come gestisci i tasti numerici? Molti di questi problemi sono stati risolti e sono discussi nella documentazione degli strumenti XML (sopra).

La velocità è importante per te? O è importante la facilità d'uso? Esiste un modulo C++ puro (tutto scritto in C++), un modulo Python puro (tutto scritto in Python) e un modulo Python C Extension (scritto in C++, ma con wrapping così Python può chiamarlo). Il modulo C++ e il modulo Python C Extension sono ordini di grandezza più veloci, ma ovviamente richiedono la compilazione per iniziare. Il modulo Python dovrebbe funzionare, ma è più lento:

8

Ho scritto una semplice funzione che serializza i dizionari in xml (sotto 30 righe).

utilizzo:

mydict = { 
    'name': 'The Andersson\'s', 
    'size': 4, 
    'children': { 
     'total-age': 62, 
     'child': [ 
      { 
       'name': 'Tom', 
       'sex': 'male', 
      }, 
      { 
       'name': 'Betty', 
       'sex': 'female', 
      } 
     ] 
    }, 
} 
print(dict2xml(mydict, 'family')) 

risultati:

<family name="The Andersson's" size="4"> 
     <children total-age="62"> 
       <child name="Tom" sex="male"/> 
       <child name="Betty" sex="female"/> 
     </children> 
</family> 

La sorgente completo (compreso un esempio) si possono trovare sul https://gist.github.com/reimund/5435343/

Nota: Questa funzione serializzare voci del dizionario come attributi piuttosto che nodi di testo. La modifica per supportare il testo sarebbe molto semplice.