encoding/xml

Created
Sep 15, 2023 03:02 AM
Tags
标准库
xml包实现xml解析

核心的两个函数

func Marshal(v interface{}) ([]byte, error)
将struct编码成xml,可以接收任意类型
func Unmarshal(data []byte, v interface{}) error
将xml转码成struct结构体

两个核心结构体

type Decoder struct { ... }
从输入流读取并解析xml
type Encoder struct { // contains filtered or unexpected fields }

反序列化

package main import ( "encoding/xml" "fmt" ) type Person struct { // 反引号 XMLName xml.Name `xml:"person"` Name string `xml:"name"` Age int `xml:"age"` Email string `xml:"email"` } func main() { person := Person{ Name: "tom", Age: 20, Email: "hybpjx@163.com", } // 没有缩进 //b, _ := xml.Marshal(person) // 有缩进 b, _ := xml.MarshalIndent(person, "", " ") fmt.Println(string(b)) /* <person> <name>tom</name> <age>20</age> <email>hybpjx@163.com</email> </person> */

序列化

package main import ( "encoding/xml" "fmt" ) type Person struct { // 反引号 XMLName xml.Name `xml:"person"` Name string `xml:"name"` Age int `xml:"age"` Email string `xml:"email"` } func main() { s := ` <person> <name>tom</name> <age>20</age> <email>hybpjx@163.com</email> </person> ` b := []byte(s) var p Person err := xml.Unmarshal(b, &p) if err != nil { return } fmt.Println(p) // {{ person} tom 20 hybpjx@163.com} }