2016-06-30 23 views
7

Sto scrivendo XML dal seguente struct:Vai, codifica/xml: come posso effettuare il marshalling degli elementi a chiusura automatica?

type OrderLine struct { 
    LineNumber  string `xml:"LineNumber"` 
    Product  string `xml:"Product"` 
    Ref   string `xml:"Ref"` 
    Quantity  string `xml:"Quantity"` 
    Price   string `xml:"Price"` 
    LineTotalGross string `xml:"LineTotalGross"` 
} 

Se il campo è vuoto Ref, mi piacerebbe l'elemento da visualizzare, ma essere a chiusura automatica, vale a dire

<Ref /> 

e non:

<Ref></Ref> 

per quanto ne so, questi due sono semanticamente equivalenti, ma io preferirei un auto-cl tag osing, poiché corrisponde all'output di altri sistemi. È possibile?

+4

penso che questa discussione 'go-nuts' discute stessa cosa. Ho dubbi che il golang ha il supporto di ciò che stai chiedendo. https://groups.google.com/forum/#!topic/golang-nuts/guG6iOCRu08 –

+1

Non puoi. (Bene, tranne solo 's, , , g'.) – Volker

risposta

1

Ho trovato un modo per farlo pacchetto di marshalling "hacking", ma non l'ho provato. Se vuoi che ti mostri il link, fammelo ora, poi lo posterò nei commenti di questa risposta.

Ho fatto qualche manualmente il codice:

package main 

import (
    "encoding/xml" 
    "fmt" 
    "regexp" 
    "strings" 
) 

type ParseXML struct { 
    Person struct { 
     Name  string `xml:"Name"` 
     LastName string `xml:"LastName"` 
     Test  string `xml:"Abc"` 
    } `xml:"Person"` 
} 

func main() { 

    var err error 
    var newPerson ParseXML 

    newPerson.Person.Name = "Boot" 
    newPerson.Person.LastName = "Testing" 

    var bXml []byte 
    var sXml string 
    bXml, err = xml.Marshal(newPerson) 
    checkErr(err) 

    sXml = string(bXml) 

    r, err := regexp.Compile(`<([a-zA-Z0-9]*)><(\\|\/)([a-zA-Z0-9]*)>`) 
    checkErr(err) 
    matches := r.FindAllString(sXml, -1) 

    fmt.Println(sXml) 

    if len(matches) > 0 { 
     r, err = regexp.Compile("<([a-zA-Z0-9]*)>") 
     for i := 0; i < len(matches); i++ { 

      xmlTag := r.FindString(matches[i]) 
      xmlTag = strings.Replace(xmlTag, "<", "", -1) 
      xmlTag = strings.Replace(xmlTag, ">", "", -1) 
      sXml = strings.Replace(sXml, matches[i], "<"+xmlTag+" />", -1) 

     } 
    } 

    fmt.Println("") 
    fmt.Println(sXml) 

} 

func checkErr(chk error) { 
    if chk != nil { 
     panic(chk) 
    } 
} 
Problemi correlati