You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GoLand中通过Go xml.Marshal生成SOAP请求所需嵌套XML

代码调整方案

核心修改点

  • 修正SOAP Envelope的命名空间属性定义错误,原有tag写法会把命名空间生成为子节点而非标签属性
  • 扩展Command结构体,添加对应嵌套字段的定义,即可自动生成子标签

完整修改后代码

package main

import (
	"encoding/xml"
	"fmt"
	"os"
)

type Command struct {
	XMLName       xml.Name
	Test          string `xml:"test"`
	SomeOtherTest string `xml:"someothertest"`
}

type XMLEnvelop struct {
	XMLName        xml.Name `xml:"soapenv:Envelope"`
	SoapEnvXmlns   string   `xml:"xmlns:soapenv,attr"`
	CalculatePrice Command  `xml:"soapenv:Body>CalculatePrice"`
}

func main() {
	v := &XMLEnvelop{
		SoapEnvXmlns: "http://schemas.xmlsoap.org/soap/envelope/",
		CalculatePrice: Command{
			XMLName:       xml.Name{Space: "namespace2", Local: "CalculatePrice"},
			Test:          "somevalue",
			SomeOtherTest: "somevalue",
		},
	}

	output, err := xml.MarshalIndent(v, "", "    ")
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}

	os.Stdout.Write(output)
}

输出结果

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <CalculatePrice xmlns="namespace2">
            <test>somevalue</test>
            <someothertest>somevalue</someothertest>
        </CalculatePrice>
    </soapenv:Body>
</soapenv:Envelope>

说明

  1. 结构体字段tag加,attr标记后,该字段会被序列化为当前标签的属性,修正了原来命名空间被生成成子节点的问题
  2. Command结构体中新增的字段tag指定对应XML子标签的名称,序列化时会自动嵌套到CalculatePrice标签内部,直接给字段赋值即可设置子标签的文本内容

内容的提问来源于stack exchange,提问作者Farshad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:54:01