视频来源:B站《golang入门到项目实战 [2021最新Go语言教程,没有废话,纯干货!持续更新中...]》
一边学习一边整理老师的课程内容及试验笔记,并与大家分享,侵权即删,谢谢支持!
附上汇总贴:Go语言自学系列 | 汇总_COCOgsta的博客-CSDN博客_go语言自学
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
}
写xml到输出流
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 Marshal() {
p := Person {
Name: "tom",
Age: 20,
Email: "tom@gmail.com",
}
// b, _ := xml.Marshal(p)
// 有缩进格式
b, _ := xml.MarshalIndent(p, " ", " ")
fmt.Printf("%v\n", string(b))
}
func main() {
Marshal()
}
运行结果
[Running] go run "/Users/guoliang/Documents/Source Code/go/test.go"
<person>
<name>tom</name>
<age>20</age>
<email>tom@gmail.com</email>
</person>
也可以读写文件
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:"name"`
Age int `xml:"age"`
Email string `xml:"email"`
}
func read() {
b, _ := ioutil.ReadFile("a.xml")
var p Person
xml.Unmarshal(b, &p)
fmt.Printf("p: %v\n", p)
}
func write() {
p := Person{
Name: "tom",
Age: 20,
Email: "tom@gmail.com",
}
f, _ := os.OpenFile("a.xml", os.O_WRONLY, 0777)
defer f.Close()
e := xml.NewEncoder(f)
e.Encode(p)
}
func main() {
read()
}
运行结果
[Running] go run "/Users/guoliang/Documents/Source Code/go/test.go"
p: {{ person} tom 20 tom@gmail.com}
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:"name"`
Age int `xml:"age"`
Email string `xml:"email"`
}
func read() {
b, _ := ioutil.ReadFile("a.xml")
var p Person
xml.Unmarshal(b, &p)
fmt.Printf("p: %v\n", p)
}
func write() {
p := Person{
Name: "tom",
Age: 20,
Email: "tom@gmail.com",
}
f, _ := os.OpenFile("a.xml", os.O_WRONLY, 0777)
defer f.Close()
e := xml.NewEncoder(f)
e.Encode(p)
}
func main() {
write()
}
运行结果
<person><name>tom</name><age>20</age><email>tom@gmail.com</email></person>