Go XML Marshal:切片的意外输出

Go XML Marshal: Unintended Output of Slice

存在一个结构,其成员之一是切片:

type Package struct {
    Name string
    ...
    Files []File
}

type File struct {
    Name string
    ...
}

我用 encoding/xml 编组了这个结构。这是我得到的:

<Package>
    <Name>example</Name>
    <Files>
        <Name>Example1</Name>
    </Files>
    <Files>
        <Name>Example2</Name>
    </Files>
</Package>

这不是我想要的行为。我想将其编组为这种格式:

<Package>
    <Name>example</Name>
    <Files>
        <File>
            <Name>Example1</Name>
        </File>
        <File>
            <Name>Example2</Name>
        </File>
    </Files>
</Package>

刚接触Golang,对它的切片和编组机制了解不多。虽然这听起来像是一个愚蠢的问题,但我怎样才能达到预期的(第二种)格式?

编组和解组规则在 encoding/xml. For example the section on xml.Marshal 的相关文档中有很好的说明:

If a field uses a tag "a>b>c", then the element c will be nested inside parent elements a and b. Fields that appear next to each other that name the same parent will be enclosed in one XML element.


所以你应该能够用这个实现你想要的:

type Package struct {
    Name  string
    Files []File `xml:"Files>File"`
}

// this also works
type Package struct {
    Name  string
    Files []File `xml:">File"`
}

https://play.golang.org/p/gg-6Tj3WNnV