Go语言自学系列 | golang标准库encoding/xml

视频来源: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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值