Golang笔记

golang 原生xml 转json

golang 原生xml 转json

新建一个xml 文件 Employees.xml

<?xml version="1.0"?>
  <company>
          <staff>
                  <id>101</id>
                  <firstname>Derek</firstname>
                  <lastname>Young</lastname>
                  <username>derekyoung</username>
          </staff>
          <staff>
                  <id>102</id>
                  <firstname>John</firstname>
                  <lastname>Smith</lastname>
                  <username>johnsmith</username>
          </staff>
  </company>

go 代码:

package main

 import (
         "encoding/json"
         "encoding/xml"
         "fmt"
         "io/ioutil"
         "os"
 )

 type jsonStaff struct {
         ID        int
         FirstName string
         LastName  string
         UserName  string
 }

 type Staff struct {
         XMLName   xml.Name `xml:"staff"`
         ID        int      `xml:"id"`
         FirstName string   `xml:"firstname"`
         LastName  string   `xml:"lastname"`
         UserName  string   `xml:"username"`
 }

 type Company struct {
         XMLName xml.Name `xml:"company"`
         Staffs  []Staff  `xml:"staff"`
 }

 func (s Staff) String() string {
         return fmt.Sprintf("\t ID : %d - FirstName : %s - LastName : %s - UserName : %s \n", s.ID, s.FirstName, s.LastName, s.UserName)
 }

 func main() {
         xmlFile, err := os.Open("Employees.xml")
         if err != nil {
                 fmt.Println("Error opening file:", err)
                 return
         }
         defer xmlFile.Close()

         XMLdata, _ := ioutil.ReadAll(xmlFile)

         var c Company
         xml.Unmarshal(XMLdata, &c)

         // sanity check - XML level
         fmt.Println(c.Staffs)

         // convert to JSON
         var oneStaff jsonStaff
         var allStaffs []jsonStaff

         for _, value := range c.Staffs {
                 oneStaff.ID = value.ID
                 oneStaff.FirstName = value.FirstName
                 oneStaff.LastName = value.LastName
                 oneStaff.UserName = value.UserName

                 allStaffs = append(allStaffs, oneStaff)
         }

         jsonData, err := json.Marshal(allStaffs)

         if err != nil {
                 fmt.Println(err)
                 os.Exit(1)
         }

         // sanity check - JSON level

         fmt.Println(string(jsonData))

         // now write to JSON file

         jsonFile, err := os.Create("./Employees.json")

         if err != nil {
                 fmt.Println(err)
         }
         defer jsonFile.Close()

         jsonFile.Write(jsonData)
         jsonFile.Close()

 }

输出:

[
     {
         "ID": 101,
         "FirstName": "Derek",
         "LastName": "Young",
         "UserName": "derekyoung"
     },
     {
         "ID": 102,
         "FirstName": "John",
         "LastName": "Smith",
         "UserName": "johnsmith"
     }
 ]

也可以使用第三方库:

goxml2json https://github.com/basgys/goxml2json 28 mxj https://github.com/clbanning/mxj 20

本文网址: https://golangnote.com/topic/139.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles