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 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?