2013-04-24 32 views
5

我想才達到以下XML輸出編組XML轉到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> 

我有一個XML輸出非常接近,但是我已經無法編碼爲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-

如何將xmlns編碼到CreateHostedZoneRequest中?

回答

3

你可以做到這一點,這可能不是最完美的解決方案,但似乎工作

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

生產

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

我也有類似的問題。爲解組方法的文檔(http://golang.org/pkg/encoding/xml/#Unmarshal)有:

如果XMLName場的形式爲「名」或「命名空間URL名稱」的相關標籤,XML元素必須有給定名稱(和,可選,名稱空間),否則Unmarshal會返回錯誤。

在結構標籤使用 「命名空間URL名稱」:

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

應該產生:

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