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


GO MarshalIndent用法及代码示例


GO语言"encoding/xml"包中"MarshalIndent"函数的用法及代码示例。

用法:

func MarshalIndent(v any, prefix, indent string)([]byte, error)

MarshalIndent 的工作方式与 Marshal 类似,但每个 XML 元素都以新的缩进行开始,该行以前缀开头,后跟根据嵌套深度的一个或多个缩进副本。

例子:

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

	output, err := xml.MarshalIndent(v, "  ", "    ")
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}

	os.Stdout.Write(output)
}

输出:

  <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大神的英文原创作品 MarshalIndent。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。