doutuo3575 2013-04-24 21:05
浏览 29
已采纳

编组XML Go XMLName + xmlns

I am trying to achive the following XML output

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

I have the following which outputs XML that is very close however I have been unable to encode into 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-

How can I encode xmlns into the CreateHostedZoneRequest?

  • 写回答

2条回答 默认 最新

  • dongzheng4556 2013-04-24 21:16
    关注

    You can do this, which possibly isn't the most elegant solution, but seems to work

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序