有没有一种方法只能在go xml包中编码XML开头标签?

I have a type,

type Example struct {
  XMLName xml.Name `xml:"example example"`
  Attr1 string `xml:"attr1,attr"`
}

If I try to encode this using xml.Encoder to stdout writer,

enc := xml.NewEncoder(os.Stdout)
v := &Example{Attr1: "attr1"}

if err := enc.Encode(v); err != nil {
    fmt.Printf("error: %v
", err)
}

it encodes this element with the closing tag, i.e.

<example xmlns="example" attr1="attr1"></example>

But I want to encode only the opening tag, i.e.

<example xmlns="example" attr1="attr1">

Is this possible?

You can implement Marshaller interface for your struct and do whatever you want.

As a hack you can add a dummy member to the parent struct and do custom stuff there:

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
}