dongruolin5324 2012-12-10 01:12
浏览 30
已采纳

在go中将数组编组为单个xml元素

I'm learning Go by writing a program that generates files in Collada format, which describes geometry using XML.

You annotate your structs and almost everything works as you'd expect, except I can't figure out how to marshal arrays into one XML element - I always end up generating N elements.

In other words, I'd like

<input>
    <p>0 1 2</p>
</input> 

instead of

<input>
    <p>0</p>
    <p>1</p>
    <p>2</p>
</input> 

The code is as follows

package main

import (
    "encoding/xml"
    "os"
)

func main() {
    type Vert struct {
        XMLName xml.Name    `xml:"input"`
        Indices     []int   `xml:"p"`
    }

    v := &Vert{Indices:[]int{0, 1, 2}}
    output, err := xml.MarshalIndent(v, "", "    ")
    if err == nil {
        os.Stdout.Write(output)
    }
}

Various comments (and code) from encoding/xml/marshal.go seem to imply that I'm out of luck:

// Marshal handles an array or slice by marshalling each of the elements.
// Slices and arrays iterate over the elements. They do not have an enclosing tag.

Strangely, if I change my array type to uint8, the array is not marshalled at all.

If I am out of luck, I'll probably use the xml:",innerxml" annotation to substitute the array myself.

  • 写回答

2条回答 默认 最新

  • douqu2712 2012-12-10 06:13
    关注

    As you guessed, encoding/xml will not be able to do this out-of-the-box. You can do something like this instead:

    import (
        "strconv"
        "strings"
    )
    
    type Vert struct {
        P string `xml:"p"`
    }
    
    func (v *Vert) SetIndices(indices []int) {
        s := make([]string, len(indices))
        for i := range indices {
            s[i] = strconv.FormatInt(int64(indices[i]), 10)
        }
        v.P = strings.Join(s, " ")
    }
    

    EDIT: I originally wrote a getter instead of setter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失