2013-04-24 11 views
5

Ich versuche, die folgende XML-AusgabeRangierung 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> 

Ich habe die folgenden, die XML gibt an achive, die sehr nahe ist jedoch habe ich es nicht gelungen, in CreateHostedZoneRequest

zu kodieren

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 
} 

Wie kann ich xmlns in die CreateHostedZoneRequest codieren

Antwort

3

Sie können dies tun, die möglicherweise nicht die eleganteste Lösung ist, scheint aber

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/", 
} 

Producing

<?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

Ich hatte eine ähnliche Frage zu arbeiten. Die Dokumentation für die Abstellungsmethode (http://golang.org/pkg/encoding/xml/#Unmarshal) hat:

Wenn das XMLName Feld einen zugehörigen Tag der Form „Namen“ oder „Namespace-URL-Name“, so muss das XML-Element die angegebenen Namen (und, optional, Namespace) oder sonst gibt Unmarshal einen Fehler zurück.

Verwendung von "Namespace-URL-Name" in der Struktur tag:

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

produzieren sollte:

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