码迷,mamicode.com
首页 > 编程语言 > 详细

go语言学习 ---struct 对象的序列化和反序列化(xml)

时间:2019-06-17 11:12:35      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:package   string   设置   sha   span   uil   mars   序列   ror   

实例1:

//main
package main

import (
	"encoding/xml"
	"fmt"
)

type person struct {
	Name string
	Age  int
}

func main() {
	p := person{Name: "sary", Age: 20}

	if data, err := xml.MarshalIndent(p, "", " "); err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println(string(data))
	}

}

  输出:

D:/Go/bin/go.exe build [D:/GOPATH/src/study.go]

Success: process exited with code 0.

D:/GOPATH/src/study.go/study.go.exe [D:/GOPATH/src/study.go]

<person>

<Name>sary</Name>

<Age>20</Age>

</person>

Success: process exited with code 0.

 

实例2

//main
package main

import (
	"encoding/xml"
	"fmt"
)

type person struct {
	Name string
	Age  int
}

func main() {
	p := person{Name: "sary", Age: 20}

	var data []byte
	var err error

	if data, err = xml.MarshalIndent(p, "#", " "); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(data))

	p2 := new(person)
	if err = xml.Unmarshal(data, p2); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(p2)

}

  输出:

D:/Go/bin/go.exe build [D:/GOPATH/src/study.go]

Success: process exited with code 0.

D:/GOPATH/src/study.go/study.go.exe [D:/GOPATH/src/study.go]

#<person>

# <Name>sary</Name>

# <Age>20</Age>

#</person>

&{sary 20}

Success: process exited with code 0.

实例3:(设置标签属性)

//main
package main

import (
	"encoding/xml"
	"fmt"
)

type person struct {
	Name string `xml:"Name,attr"`
	Age  int    `xml:"Age,attr"`
}

func main() {
	p := person{Name: "sary", Age: 20}

	var data []byte
	var err error

	if data, err = xml.MarshalIndent(p, "#", " "); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(data))

	p2 := new(person)
	if err = xml.Unmarshal(data, p2); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(p2)

}

  输出:

D:/Go/bin/go.exe build [D:/GOPATH/src/study.go]

Success: process exited with code 0.

D:/GOPATH/src/study.go/study.go.exe [D:/GOPATH/src/study.go]

#<person Name="sary" Age="20"></person>

&{sary 20}

Success: process exited with code 0.

 

go语言学习 ---struct 对象的序列化和反序列化(xml)

标签:package   string   设置   sha   span   uil   mars   序列   ror   

原文地址:https://www.cnblogs.com/saryli/p/11038085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!