当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO Encoder用法及代码示例


GO语言"encoding/xml"包中"Encoder"类型的用法及代码示例。

编码器将 XML 数据写入输出流。

用法:

type Encoder struct {
    // contains filtered or unexported fields
}

例子:

package main

import (
	"encoding/xml"
	"fmt"
	"os"
)

func main() {
	type Address struct {
		City, State string
	}
	type Person struct {
		XMLName   xml.Name `xml:"person"`
		Id        int      `xml:"id,attr"`
		FirstName string   `xml:"name>first"`
		LastName  string   `xml:"name>last"`
		Age       int      `xml:"age"`
		Height    float32  `xml:"height,omitempty"`
		Married   bool
		Address
		Comment string `xml:",comment"`
	}

	v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
	v.Comment = " Need more details. "
	v.Address = Address{"Hanga Roa", "Easter Island"}

	enc := xml.NewEncoder(os.Stdout)
	enc.Indent("  ", "    ")
	if err := enc.Encode(v); err != nil {
		fmt.Printf("error: %v\n", err)
	}

}

输出:

  <person id="13">
      <name>
          <first>John</first>
          <last>Doe</last>
      </name>
      <age>42</age>
      <Married>false</Married>
      <City>Hanga Roa</City>
      <State>Easter Island</State>
      <!-- Need more details. -->
  </person>

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Encoder。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。