Go实战--xml与json相互转换(The way to go)

前端之家收集整理的这篇文章主要介绍了Go实战--xml与json相互转换(The way to go)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

生命不止,继续 go go go !

之前写了两篇博客,分别介绍了go中的encoding/json和encoding/xml,有很多相识之处。

json和xml的恩恩怨怨还没有结束,在实战中我们会用到XML与json的相互转化,没有太难懂的地方。

xml转json

package main

import (
    "encoding/json"
    "encoding/xml"
    "fmt"
)

type DataFormat struct {
    ProductList []struct {
        Sku      string `xml:"sku" json:"sku"`
        Quantity int    `xml:"quantity" json:"quantity"`
    } `xml:"Product" json:"products"`
}

func main() {
    xmlData := []byte(`<?xml version="1.0" encoding="UTF-8" ?>
<ProductList>
    <Product>
        <sku>ABC123</sku>
        <quantity>2</quantity>
    </Product>
    <Product>
        <sku>ABC123</sku>
        <quantity>2</quantity>
    </Product>
</ProductList>`)

    data := &DataFormat{}
    err := xml.Unmarshal(xmlData,data)
    if nil != err {
        fmt.Println("Error unmarshalling from XML",err)
        return
    }

    result,err := json.Marshal(data)
    if nil != err {
        fmt.Println("Error marshalling to JSON",err)
        return
    }

    fmt.Printf("%s\n",result)
}

输出
{“products”:[{“sku”:”ABC123”,”quantity”:2},{“sku”:”ABC123”,”quantity”:2}]}

xml文件转json文件
接下来,我们根据一个xml文件生产一个相应的json文件
在src文件夹下mkdir xmlfile_to_jsonfile,新建一个一个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>

代码

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()

 }

生成文件Employees.json :

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

json转xml

type Person struct {
    Id        int    `xml:"id,attr"`
    FirstName string `xml:"name>first" json:"first"`
    LastName  string `xml:"name>last" json:"last"`
}

func main() {
    j := `{"id": 10,"first": "firstname","last":"lastname"}`
    var p Person
    fmt.Println(json.Unmarshal([]byte(j),&p),p)
    out,_ := xml.MarshalIndent(p,"\t","\t")
    fmt.Println(string(out))

}

猜你在找的XML相关文章