-
Notifications
You must be signed in to change notification settings - Fork 0
/
mxjdemo.go
111 lines (97 loc) · 2.08 KB
/
mxjdemo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"fmt"
"os"
"github.com/clbanning/mxj"
)
func main() {
xml2json()
json2xml()
}
func json2xml() {
jsonValue, err := readFromFile("data.json")
if err != nil {
fmt.Println(err)
}
fmt.Println("==========")
fmt.Println("Json value:")
fmt.Println("==========")
fmt.Println(string(jsonValue))
mv, err := mxj.NewMapJson(jsonValue)
if err != nil {
fmt.Println(err)
}
fmt.Println("==========")
fmt.Println("Map value:")
fmt.Println("==========")
fmt.Println(mv)
xmlValue, err := mv.XmlIndent("", " ")
if err != nil {
fmt.Println(err)
}
fmt.Println("==========")
fmt.Println("XML value:")
fmt.Println("==========")
fmt.Println(string(xmlValue))
jsonValue2, err := mv.JsonIndent("", " ")
if err != nil {
fmt.Println(err)
}
fmt.Println("===========")
fmt.Println("back to JSON:")
fmt.Println("===========")
fmt.Println(string(jsonValue2))
}
func xml2json() {
xmlVlaue, err := readFromFile("data.xml")
if err != nil {
fmt.Println(err)
}
fmt.Println("==========")
fmt.Println("xml value:")
fmt.Println("==========")
fmt.Println(string(xmlVlaue))
mv, err := mxj.NewMapXml(xmlVlaue)
if err != nil {
fmt.Println(err)
}
fmt.Println("==========")
fmt.Println("Map value:")
fmt.Println("==========")
fmt.Println(mv, "\n")
jsonValue, err := mv.JsonIndent("", " ")
if err != nil {
fmt.Println(err)
}
fmt.Println("==========")
fmt.Println("json value:")
fmt.Println("==========")
fmt.Println(string(jsonValue))
xmlValue2, err := mv.XmlIndent("", " ")
if err != nil {
fmt.Println(err)
}
fmt.Println("============")
fmt.Println("back to xml:")
fmt.Println("============")
fmt.Println(string(xmlValue2))
}
func readFromFile(fileName string) ([]byte, error) {
fh, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer fh.Close()
fs, _ := fh.Stat()
fileData := make([]byte, fs.Size())
n, err := fh.Read(fileData)
if err != nil {
return nil, err
}
if int64(n) != fs.Size() {
fmt.Println("n:", n, "fs.Size():", fs.Size())
return nil, err
}
fmt.Println("Read ", n, " bytes from ", fileName)
return fileData, nil
}