我有一个类型,
type Example struct {
XMLName xml.Name `xml:"example example"`
Attr1 string `xml:"attr1,attr"`
}
如果我尝试使用xml.Encoder对stdout writer进行编码,
enc := xml.NewEncoder(os.Stdout)
v := &Example{Attr1: "attr1"}
if err := enc.Encode(v); err != nil {
fmt.Printf("error: %v\n", err)
}
它使用结束标记对此元素进行编码,即
<example xmlns="example" attr1="attr1"></example>
但我想只编码开头标签,即
<example xmlns="example" attr1="attr1">
这可能吗?
您可以为您的结构实现Marshaller
接口并执行您想要的任何操作。
作为一个黑客,你可以添加一个虚拟成员到父结构并在那里做自定义的东西:
type ExampleInner struct {
}
func (ExampleInner) MarshalXML(e *Encoder, start StartElement) error {
// Do your custom stuff here
return nil
}
type Example struct {
XMLName xml.Name `xml:"example example"`
Attr1 string `xml:"attr1,attr"`
Inner ExampleInner
}