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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。