-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLMarshal.go
79 lines (68 loc) · 1.43 KB
/
XMLMarshal.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
/*
XMLMarshal.go
本程序将将Person结构转换成xml字符串,再把xml字符串转换成go结构体并输出
*/
package main
import (
"encoding/xml"
"fmt"
"os"
)
type Person struct {
XMLName Name `xml:"person"`
Name Name `xml:"name"`
Email []Email `xml:"email"`
}
type Name struct {
Family string `xml:"family"`
Personal string `xml:"personal"`
}
type Email struct {
Type string `xml:"type,attr"`
Address string `xml:",chardata"`
}
func main() {
p := Person{
Name: Name{
Family: "Chu",
Personal: "Tianle",
},
Email: []Email{
Email{
Type: "life",
Address: "[email protected]",
},
Email{
Type: "work",
Address: "[email protected]",
},
},
}
// marshal操作
bytes, err := xml.Marshal(p)
checkError(err)
str := string(bytes)
fmt.Println("The XML string is: \n" + str)
/*
str := `<?xml version="1.0" encoding="utf-8"?>
<person>
<name>
<family>Newmarch</family>
<personal>Jan</personal>
</name>
<email type="personal">[email protected]</email>
<email type="work">[email protected]</email>
</person>`
*/
var person Person
err = xml.Unmarshal([]byte(str), &person)
checkError(err)
fmt.Println("Family name: \"" + person.Name.Family + "\"")
fmt.Println("Second email address: \"" + person.Email[1].Address + "\"")
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}