如何使用一个字段作为标记,另一个字段作为值将go struct序列化为XML
我有一些结构:如何使用一个字段作为标记,另一个字段作为值将go struct序列化为XML,xml,go,Xml,Go,我有一些结构: 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> </toke
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>
类型令牌结构{
}
类型标记结构{
类型字符串
值字符串
}
我需要获取XML文件作为输出:
x
Y
Z
其中关键字、标识符或符号是字段类型的值,x、y、x是字段值的值
具体来说,我不需要将每个令牌包装到标记中。有多种类型的令牌,但对于某些值,只有一种类型
标准的库编码/xml并没有提供一个现成的解决方案。它似乎只提供将字段名用作标记的功能您可以使用encoding/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))
}
我已经用“github.com/beevik/etree”包解决了这个问题。它们提供了一种简单的方法
package main
import (
"os"
"github.com/beevik/etree"
)
type Token struct {
Type string
Value string
}
var x = Token{Type: "keyword", Value: "x",}
var y = Token{Type: "identifier", Value: "y"}
var z = Token{Type: "symbol", Value: "z"}
var w = []Token {x, y, z}
func main() {
doc := etree.NewDocument()
doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
tokens := doc.CreateElement("tokens")
for i := range w {
elem := tokens.CreateElement(w[i].Type)
elem.CreateText(w[i].Value)
}
doc.Indent(2)
doc.WriteTo(os.Stdout)
}
使用结构标记,如
`xml:“关键字”`
。文档甚至为此提供了一个示例,它返回x y z,我不需要将其包装在标记中,并且标记不是字段“关键字”、“标识符”和“符号”的结构。它具有与特定值相关的特定类型。类型应出现在标记中。您可以将其重命名为标记。