在Go中将任意XML属性编组为一个元素?

I need to marshal in extra attributes on an element at runtime. I've tried this:

type Meh struct {
    XMLName xml.Name
    Attrs []xml.Attr
}

Meh{
    Attrs: []xml.Attr{
        xml.Attr{xml.Name{Local: "hi"}, "there"},
    },  
}

But the fields are treated as new elements:

<Meh><Attrs><Name></Name><Value>there</Value></Attrs></Meh>

If I add the tag xml:",attr" to the Attr field, it expects a []byte or string specifying the contents of a single attribute.

How do I specify attributes at runtime? How do I annotate the type to provide field(s) for this?

You might try working directly with templates. Example:

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)
}

Output:

<Meh hi="there" um="I said &#34;hello?&#34;">
</Meh>