2013-04-24 33 views
5

sto cercando di achive il seguente output XMLMarshalling XML Go XMLName + xmlns

<?xml version="1.0" encoding="UTF-8"?> 

<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> 
    <Name>DNS domain name</Name> 
    <CallerReference>unique description</CallerReference> 
    <HostedZoneConfig> 
     <Comment>optional comment</Comment> 
    </HostedZoneConfig> 
</CreateHostedZoneRequest> 

ho il seguente, che emette XML che è molto vicino ma sono stato in grado di codificare in CreateHostedZoneRequest

xmlns = "https://route53.amazonaws.com/doc/2012-12-12/

package main 

import "fmt" 
import "encoding/xml" 

type ZoneRequest struct { 
    Name   string 
    CallerReference string 
    Comment   string `xml:"HostedZoneConfig>Comment"` 
} 

var zoneRequest = ZoneRequest{ 
    Name:   "DNS domain name", 
    CallerReference: "unique description", 
    Comment:   "optional comment", 
} 

func main() { 
    tmp, _ := createHostedZoneXML(zoneRequest) 
    fmt.Println(tmp) 
} 

func createHostedZoneXML(zoneRequest ZoneRequest) (response string, err error) { 
    tmp := struct { 
    ZoneRequest 
    XMLName struct{} `xml:"CreateHostedZoneRequest"` 
    }{ZoneRequest: zoneRequest} 

    byteXML, err := xml.MarshalIndent(tmp, "", ` `) 
    if err != nil { 
    return "", err 
    } 
    response = xml.Header + string(byteXML) 
    return 
} 

http://play.golang.org/p/pyK76VPD5-

Come posso codificare xmlns in CreateHostedZoneRequest?

risposta

3

si può fare questo, che forse non è la soluzione più elegante, ma sembra funzionare

Playground link

type ZoneRequest struct { 
    Name   string 
    CallerReference string 
    Comment   string `xml:"HostedZoneConfig>Comment"` 
    Xmlns   string `xml:"xmlns,attr"` 
} 

var zoneRequest = ZoneRequest{ 
    Name:   "DNS domain name", 
    CallerReference: "unique description", 
    Comment:   "optional comment", 
    Xmlns:   "https://route53.amazonaws.com/doc/2012-12-12/", 
} 

Produrre

<?xml version="1.0" encoding="UTF-8"?> 

<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> 
    <Name>DNS domain name</Name> 
    <CallerReference>unique description</CallerReference> 
    <HostedZoneConfig> 
     <Comment>optional comment</Comment> 
    </HostedZoneConfig> 
</CreateHostedZoneRequest> 
5

avevo una domanda simile. La documentazione per il metodo Unmarshal (http://golang.org/pkg/encoding/xml/#Unmarshal) avere:

Se il campo XMLName ha un tag associato della forma "nome" o "nome del namespace-URL", l'elemento XML deve avere il nome dato (e, facoltativamente, spazio dei nomi) oppure Unmarshal restituisce un errore.

L'utilizzo di "nome del namespace-URL" nel tag struct:

type ZoneRequest struct { 
    XMLName xml.Name `xml:"https://route53.amazonaws.com/doc/2012-12-12/ CreateHostedZoneRequest"` 
} 

dovrebbe produrre:

<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2012-12-12/"> 
Problemi correlati