一、读写xml文件
golang的”encoding/xml”模块有 xml.Unmarshal() 方法和 xml.Marshal() 方法。前者用于格式化读取 xml 文件,后者用于格式化写 xml 文件。操作之前我们先准备一个测试文件notes.xml,内容如下:
<note>
<to>Admin</to>
<from>www.361way.com</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
1、 xml.Unmarshal()读 xml
代码如下:
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
)
type Notes struct {
To string `xml:"to"`
From string `xml:"from"`
Heading string `xml:"heading"`
Body string `xml:"body"`
}
func main() {
data, _ := ioutil.ReadFile("notes.xml")
note := &Notes{}
_ = xml.Unmarshal([]byte(data), ¬e)
fmt.Println(note.To)
fmt.Println(note.From)
fmt.Println(note.Heading)
fmt.Println(note.Body)
}
上面使用ioutil.ReadFile()方法读取后,返回byte类型的slice类型的文件,然后再交引 Unmarshal进行处理。
2、 xml.Marshal写xml文件
写xml文件的代码如下:
package main
import (
"encoding/xml"
"io/ioutil"
)
type notes struct {
To string `xml:"to"`
From string `xml:"from"`
Heading string `xml:"heading"`
Body string `xml:"body"`
}
func main() {
note := ¬es{To: "Nicky",
From: "Rock",
Heading: "Meeting",
Body: "Meeting at 5pm!",
}
file, _ := xml.MarshalIndent(note, "", " ")
_ = ioutil.WriteFile("notes1.xml", file, 0644)
}
二、读写json文件
之前也写过处理json文件的总结:https://www.361way.com/go-json/5859.html ,本篇这里再搞两个示例,本篇写json文件使用的json.MarshalIndent方法,读文件使用的json.Unmarshal方法。
1、写json文件
package main
import (
"encoding/json"
"io/ioutil"
)
type Salary struct {
Basic, HRA, TA float64
}
type Employee struct {
FirstName, LastName, Email string
Age int
MonthlySalary []Salary
}
func main() {
data := Employee{
FirstName: "Mark",
LastName: "Jones",
Email: "mark@gmail.com",
Age: 25,
MonthlySalary: []Salary{
Salary{
Basic: 15000.00,
HRA: 5000.00,
TA: 2000.00,
},
Salary{
Basic: 16000.00,
HRA: 5000.00,
TA: 2100.00,
},
Salary{
Basic: 17000.00,
HRA: 5000.00,
TA: 2200.00,
},
},
}
file, _ := json.MarshalIndent(data, "", " ")
_ = ioutil.WriteFile("test.json", file, 0644)
}
2、读json文件
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type CatlogNodes struct {
CatlogNodes []Catlog `json:"catlog_nodes"`
}
type Catlog struct {
Product_id string `json: "product_id"`
Quantity int `json: "quantity"`
}
func main() {
file, _ := ioutil.ReadFile("test.json")
data := CatlogNodes{}
_ = json.Unmarshal([]byte(file), &data)
for i := 0; i < len(data.CatlogNodes); i++ {
fmt.Println("Product Id: ", data.CatlogNodes[i].Product_id)
fmt.Println("Quantity: ", data.CatlogNodes[i].Quantity)
}
}
三、读写文本文件
1、写文本文件
package main
import (
"bufio"
"log"
"os"
)
func main() {
sampledata := []string{"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Nunc a mi dapibus, faucibus mauris eu, fermentum ligula.",
"Donec in mauris ut justo eleifend dapibus.",
"Donec eu erat sit amet velit auctor tempus id eget mauris.",
}
file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
datawriter := bufio.NewWriter(file)
for _, data := range sampledata {
_, _ = datawriter.WriteString(data + "\n")
}
datawriter.Flush()
file.Close()
}
2、读text文件
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var txtlines []string
for scanner.Scan() {
txtlines = append(txtlines, scanner.Text())
}
file.Close()
for _, eachline := range txtlines {
fmt.Println(eachline)
}
}
四、读写csv文件
1、写csv文件
package main
import (
"encoding/csv"
"log"
"os"
)
func main() {
rows := [][]string{
{"Name", "City", "Language"},
{"Pinky", "London", "Python"},
{"Nicky", "Paris", "Golang"},
{"Micky", "Tokyo", "Php"},
}
csvfile, err := os.Create("test.csv")
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
csvwriter := csv.NewWriter(csvfile)
for _, row := range rows {
_ = csvwriter.Write(row)
}
csvwriter.Flush()
csvfile.Close()
}
2、读csv文件
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.csv")
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var txtlines []string
for scanner.Scan() {
txtlines = append(txtlines, scanner.Text())
}
file.Close()
for _, eachline := range txtlines {
fmt.Println(eachline)
}
}