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

使用Golang encoding/xml包生成含重复item的SOAP XML问题

解决Golang encoding/xml生成重复的SOAP XML问题

我来帮你搞定这个SOAP XML生成的问题~你遇到的核心问题应该是结构体定义没对齐XML的层级要求,导致没法根据recipients切片正确重复生成。下面是修正后的完整实现方案:

正确的结构体定义

encoding/xml包完全依赖结构体的tag来映射XML节点,所以必须让结构体层级和你期望的XML结构严格对应:

package main

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

// SOAP信封顶层结构,带命名空间属性
type Envelope struct {
    XMLName xml.Name `xml:"soapenv:Envelope"`
    SoapEnv string   `xml:"xmlns:soapenv,attr"`
    Body    Body     `xml:"soapenv:Body"`
}

// SOAP Body部分
type Body struct {
    SendDetailRequest SendDetail `xml:"SendDetail"`
}

// 包含多个item的容器,Items字段是切片类型,对应重复的<item>节点
type SendDetail struct {
    Items []Item `xml:"item"`
}

// 单个item节点,里面是单个Mobile字段
type Item struct {
    Mobile string `xml:"Mobile"`
}

完整生成代码

接下来把recipients切片转换成Item切片,再组装成完整的SOAP结构,最后生成XML:

func main() {
    // 模拟你的recipients手机号切片
    recipients := []string{"num1", "num2", "num3"}

    // 将手机号逐个转换成Item结构体
    var items []Item
    for _, mobile := range recipients {
        items = append(items, Item{Mobile: mobile})
    }

    // 组装整个SOAP请求结构
    envelope := Envelope{
        SoapEnv: "http://schemas.xmlsoap.org/soap/envelope/",
        Body: Body{
            SendDetailRequest: SendDetail{
                Items: items,
            },
        },
    }

    // 生成格式化的XML(带缩进,方便查看)
    xmlData, err := xml.MarshalIndent(envelope, "", "  ")
    if err != nil {
        fmt.Printf("生成XML失败: %v\n", err)
        os.Exit(1)
    }

    // 加上XML声明后输出
    fmt.Println(xml.Header + string(xmlData))
}

预期输出的XML结构

运行上面的代码后,会生成完全符合你需求的SOAP XML:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <SendDetail>
      <item>
        <Mobile>num1</Mobile>
      </item>
      <item>
        <Mobile>num2</Mobile>
      </item>
      <item>
        <Mobile>num3</Mobile>
      </item>
    </SendDetail>
  </soapenv:Body>
</soapenv:Envelope>

你之前的错误点分析

你提到之前把item结构体里的Mobile定义成了[]string,这会导致每个节点下生成多个,而不是每个对应一个手机号;另外大概率你没有在SendDetail里定义切片类型的字段来承载多个item,而是直接放了单个item结构体,所以只能生成一个节点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:38:28