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

Posted saryli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言学习 ---struct 对象的序列化和反序列化(xml)相关的知识,希望对你有一定的参考价值。

实例1:

//main
package main

import (
	"encoding/xml"
	"fmt"
)

type person struct 
	Name string
	Age  int


func main() 
	p := personName: "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 := personName: "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 := personName: "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)的主要内容,如果未能解决你的问题,请参考以下文章

Go语言 Marshal 序列化和反序列化

Golang---序列化和反序列化

Go语言的JSON输入(解码)(反序列化)之struct存储

python的struct模块

JSON 序列化和反序列化 In Go

Java基础学习总结——Java对象的序列化和反序列化