dsb0003795 2018-04-04 08:22
浏览 277
已采纳

使用Golang中的encoding / xml包制作soap xml

I want to make a sample xml that repeats a field depending on the value of the slice. But the final result is not as desired.

XML that I want to create

        recipients = ["num1","num2",...]

        //Start XML
        .
        .
        .
        <SendDetail>
            <item><Mobile>num1</Mobile></item>
            <item><Mobile>num2</Mobile></item>
            ...
        </SendDetail>  

The number of repetitions of depends on the length of the slice of recipients and its values.

My Code

        type item struct {
            Mobile  []string `xml:"Mobile"`
        }
        type sendDetail struct {
            Item *[]item `xml:"item"`
        }   


        SendDetail: &sendDetail{
                Item:&[]item{
                    item{
                        Mobile:recipients,
                    },
                },
            },

Result

      <SendDetail>
        <item>
          <Mobile>num1</Mobile>
          <Mobile>num2</Mobile>
        </item>
      </SendDetail>

Any pointers will be appreciated.

  • 写回答

2条回答 默认 最新

  • dongzhong1891 2018-04-04 08:40
    关注

    In your XML inside an <item> there is only a single <Mobile> tag. You don't want to repeat the <Mobile> tag but the <item> tag. So in Go you have to create a new Item for each number.

    Model it like this:

    type Item struct {
        Mobile string `xml:"Mobile"`
    }
    
    type SendDetail struct {
        Items []*Item `xml:"item"`
    }
    

    Example using the model:

    recipients := []string{"num1", "num2"}
    
    sd := &SendDetail{}
    for _, recipient := range recipients {
        sd.Items = append(sd.Items, &Item{Mobile: recipient})
    }
    
    data, err := xml.MarshalIndent(sd, "", "  ")
    if err != nil {
        panic(err)
    }
    
    fmt.Println(string(data))
    

    Output (try it on the Go Playground):

    <SendDetail>
      <item>
        <Mobile>num1</Mobile>
      </item>
      <item>
        <Mobile>num2</Mobile>
      </item>
    </SendDetail>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀