有没有办法只在go xml包中编码XML开始标记?

问题描述 投票:-2回答:1

我有一个类型,

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">

这可能吗?

xml go encoding
1个回答
0
投票

您可以为您的结构实现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
}
© www.soinside.com 2019 - 2024. All rights reserved.