Mars中元素中的Marshal任意XML属性?

时间:2012-05-31 06:00:30

标签: xml go

我需要在运行时封送元素的额外属性。我试过这个:

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

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

但这些字段被视为新元素:

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

如果我将标记xml:",attr"添加到Attr字段,则需要[]bytestring指定单个属性的内容。

如何在运行时指定属性?如何注释类型以为此提供字段?

1 个答案:

答案 0 :(得分:2)

您可以尝试直接使用模板。例如:

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 &#34;hello?&#34;">
</Meh>