我有一些结构:
type Tokens struct {
}
type Token struct {
Type string
Value string
}
I need to get XML file as the output:
<tokens>
<keyword> x</keyword>
<identifier> y </identifier>
<symbol> z </symbol>
</tokens>
其中keyword, identifier or symbol是Type字段的值,x,y,x是Value字段的值
具体来说,我不需要将每个标记包装到标签中。 token 有多种类型,但对于某些值只有一种类型。
标准库 encoding/xml 没有为此提供现成的解决方案。貌似只提供字段名作为标签的能力
最佳答案
您可以使用编码/xml。即:
package main
import (
"encoding/xml"
"fmt"
)
func main() {
type Token struct {
Keyword string `xml:"Keyword"`
Identifier string `xml:"Identifier"`
Symbol string `xml:"Symbol"`
}
type Tokens struct {
Tokens []Token `xml:"Token"`
}
data := Tokens{[]Token{Token{Keyword: "x", Identifier: "y", Symbol: "z"},
Token{Keyword: "x1", Identifier: "y1", Symbol: "z1"},}}
xml, _ := xml.MarshalIndent(data, ""," ")
fmt.Println(string(xml))
}
关于xml - 如何使用一个字段作为标记将另一个字段作为值将 go struct 序列化为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57769800/