英文:
Marshal arbitrary XML attributes in an element in 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>
如果我在Attr
字段上添加标签xml:",attr"
,它会期望一个[]byte
或string
来指定单个属性的内容。
如何在运行时指定属性?如何注释类型以提供字段来实现这一点?
英文:
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?
答案1
得分: 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}}>`
func main() {
// 在这里定义了模板函数 "xml",用于基本转义,处理特殊字符如 "。
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>
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论