您可以尝试直接使用模板。例子:
package main
import (
"bytes"
"encoding/xml"
"fmt"
"text/template"
)
type ele struct {
Name string
Attrs []attr
}
type attr struct {
Name, Value string
}
var x = `<{{.Name}}{{range $a := .Attrs}} {{$a.Name}}="{{xml $a.Value}}"{{end}}>
</{{.Name}}>`
func main() {
// template function "xml" defined here does basic escaping,
// important for handling special characters such as ".
t := template.New("").Funcs(template.FuncMap{"xml": func(s string) string {
var b bytes.Buffer
xml.Escape(&b, []byte(s))
return b.String()
}})
template.Must(t.Parse(x))
e := ele{
Name: "Meh",
Attrs: []attr{
{"hi", "there"},
{"um", `I said "hello?"`},
},
}
b := new(bytes.Buffer)
err := t.Execute(b, e)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(b)
}
输出:
<Meh hi="there" um="I said "hello?"">
</Meh>