2015-07-02 11 views
14

Si consideri il seguente struct:uso corretto del XML annotazioni, i campi e le strutture in funzione UnmarshalXML personalizzato

type MyStruct struct { 
    Name string 
    Meta map[string]interface{} 
} 

che ha la seguente funzione UnmarshalXML:

func (m *MyStruct) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { 
    var v struct { 
     XMLName xml.Name //`xml:"myStruct"` 
     Name string `xml:"name"` 
     Meta struct { 
      Inner []byte `xml:",innerxml"` 
     } `xml:"meta"` 
    } 

    err := d.DecodeElement(&v, &start) 
    if err != nil { 
     return err 
    } 

    m.Name = v.Name 
    myMap := make(map[string]interface{}) 

    // ... do the mxj magic here ... - 

    temp := v.Meta.Inner 

    prefix := "<meta>" 
    postfix := "</meta>" 
    str := prefix + string(temp) + postfix 
    //fmt.Println(str) 
    myMxjMap, err := mxj.NewMapXml([]byte(str)) 
    myMap = myMxjMap 

    // fill myMap 
    //m.Meta = myMap 
    m.Meta = myMap["meta"].(map[string]interface{}) 
    return nil 
} 

Il mio problema con questo codice è queste righe :

prefix := "<meta>" 
postfix := "</meta>" 
str := prefix + string(temp) + postfix 
myMxjMap, err := mxj.NewMapXml([]byte(str)) 
myMap = myMxjMap 
//m.Meta = myMap 
m.Meta = myMap["meta"].(map[string]interface{}) 

mia domanda è come faccio il corretto utilizzo delle annotazioni XML (, innerxml ecc.), campi e struct, quindi non devo manualmente pre/aggiungere i tag <meta></meta> per ottenere l'intero campo Meta come una singola mappa.

L'esempio di codice completo è qui: http://play.golang.org/p/Q4_tryubO6 pacchetto

risposta

5

xml non fornisce un modo per XML unmarshal in map[string]interface{} perché non esiste un unico modo per farlo e in alcuni casi non è possibile. Una mappa non conserva l'ordine degli elementi (che è importante in XML) e non consente elementi con chiavi duplicate.

Il pacchetto mxj che è stato utilizzato nell'esempio ha alcune regole su XML arbitrario unmarshal nella mappa Go. Se i requisiti non siano in conflitto con queste regole è possibile utilizzare mxj pacchetto per fare tutto l'analisi e non utilizzare xml pacchetto a tutti:

// I am skipping error handling here 
m, _ := mxj.NewMapXml([]byte(s)) 
mm := m["myStruct"].(map[string]interface{}) 
myStruct.Name = mm["name"].(string) 
myStruct.Meta = mm["meta"].(map[string]interface{}) 

esempio completa: http://play.golang.org/p/AcPUAS0QMj

+0

Beh, non esattamente la risposta che avevo sperato , ma immagino che non possa essere aiutato. La tua proposta non funzionerebbe nella mia situazione specifica, ma almeno hai sottolineato i limiti del pacchetto Go xml, motivo per cui accetto questa risposta. – Dac0d3r

Problemi correlati