一、读写xml文件

golang的”encoding/xml”模块有 xml.Unmarshal() 方法和 xml.Marshal() 方法。前者用于格式化读取 xml 文件,后者用于格式化写 xml 文件。操作之前我们先准备一个测试文件notes.xml,内容如下:

<pre data-language="XML">```markup
<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

代码如下:

```go
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), &note)
        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文件的代码如下:

 1package main
 2import (
 3    "encoding/xml"
 4    "io/ioutil"
 5)
 6type notes struct {
 7    To      string `xml:"to"`
 8    From    string `xml:"from"`
 9    Heading string `xml:"heading"`
10    Body    string `xml:"body"`
11}
12func main() {
13    note := &notes{To: "Nicky",
14        From:    "Rock",
15        Heading: "Meeting",
16        Body:    "Meeting at 5pm!",
17    }
18    file, _ := xml.MarshalIndent(note, "", " ")
19    _ = ioutil.WriteFile("notes1.xml", file, 0644)
20}

二、读写json文件

之前也写过处理json文件的总结:https://blog.361way.com/go-json/5859.html ,本篇这里再搞两个示例,本篇写json文件使用的json.MarshalIndent方法,读文件使用的json.Unmarshal方法。

1、写json文件

 1package main
 2import (
 3    "encoding/json"
 4    "io/ioutil"
 5)
 6type Salary struct {
 7        Basic, HRA, TA float64
 8    }
 9type Employee struct {
10    FirstName, LastName, Email string
11    Age                        int
12    MonthlySalary              []Salary
13}
14func main() {
15    data := Employee{
16        FirstName: "Mark",
17        LastName:  "Jones",
18        Email:     "[email protected]",
19        Age:       25,
20        MonthlySalary: []Salary{
21            Salary{
22                Basic: 15000.00,
23                HRA:   5000.00,
24                TA:    2000.00,
25            },
26            Salary{
27                Basic: 16000.00,
28                HRA:   5000.00,
29                TA:    2100.00,
30            },
31            Salary{
32                Basic: 17000.00,
33                HRA:   5000.00,
34                TA:    2200.00,
35            },
36        },
37    }
38    file, _ := json.MarshalIndent(data, "", " ")
39    _ = ioutil.WriteFile("test.json", file, 0644)
40}

2、读json文件

 1package main
 2import (
 3    "encoding/json"
 4    "fmt"
 5    "io/ioutil"
 6)
 7type CatlogNodes struct {
 8    CatlogNodes []Catlog `json:"catlog_nodes"`
 9}
10type Catlog struct {
11    Product_id string `json: "product_id"`
12    Quantity   int    `json: "quantity"`
13}
14func main() {
15    file, _ := ioutil.ReadFile("test.json")
16    data := CatlogNodes{}
17    _ = json.Unmarshal([]byte(file), &data)
18    for i := 0; i < len(data.CatlogNodes); i++ {
19        fmt.Println("Product Id: ", data.CatlogNodes[i].Product_id)
20        fmt.Println("Quantity: ", data.CatlogNodes[i].Quantity)
21    }
22}

三、读写文本文件

1、写文本文件

 1package main
 2import (
 3    "bufio"
 4    "log"
 5    "os"
 6)
 7func main() {
 8    sampledata := []string{"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
 9        "Nunc a mi dapibus, faucibus mauris eu, fermentum ligula.",
10        "Donec in mauris ut justo eleifend dapibus.",
11        "Donec eu erat sit amet velit auctor tempus id eget mauris.",
12    }
13    file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
14    if err != nil {
15        log.Fatalf("failed creating file: %s", err)
16    }
17    datawriter := bufio.NewWriter(file)
18    for _, data := range sampledata {
19        _, _ = datawriter.WriteString(data + "\n")
20    }
21    datawriter.Flush()
22    file.Close()
23}

2、读text文件

 1package main
 2import (
 3    "bufio"
 4    "fmt"
 5    "log"
 6    "os"
 7)
 8func main() {
 9    file, err := os.Open("test.txt")
10    if err != nil {
11        log.Fatalf("failed opening file: %s", err)
12    }
13    scanner := bufio.NewScanner(file)
14    scanner.Split(bufio.ScanLines)
15    var txtlines []string
16    for scanner.Scan() {
17        txtlines = append(txtlines, scanner.Text())
18    }
19    file.Close()
20    for _, eachline := range txtlines {
21        fmt.Println(eachline)
22    }
23}

四、读写csv文件

1、写csv文件

 1package main
 2import (
 3    "encoding/csv"
 4    "log"
 5    "os"
 6)
 7func main() {
 8    rows := [][]string{
 9        {"Name", "City", "Language"},
10        {"Pinky", "London", "Python"},
11        {"Nicky", "Paris", "Golang"},
12        {"Micky", "Tokyo", "Php"},
13    }
14    csvfile, err := os.Create("test.csv")
15    if err != nil {
16        log.Fatalf("failed creating file: %s", err)
17    }
18    csvwriter := csv.NewWriter(csvfile)
19    for _, row := range rows {
20        _ = csvwriter.Write(row)
21    }
22    csvwriter.Flush()
23    csvfile.Close()
24}

2、读csv文件

 1package main
 2import (
 3    "bufio"
 4    "fmt"
 5    "log"
 6    "os"
 7)
 8func main() {
 9    file, err := os.Open("test.csv")
10    if err != nil {
11        log.Fatalf("failed opening file: %s", err)
12    }
13    scanner := bufio.NewScanner(file)
14    scanner.Split(bufio.ScanLines)
15    var txtlines []string
16    for scanner.Scan() {
17        txtlines = append(txtlines, scanner.Text())
18    }
19    file.Close()
20    for _, eachline := range txtlines {
21        fmt.Println(eachline)
22    }
23}