标签: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