-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml_demo.go
97 lines (77 loc) · 1.61 KB
/
xml_demo.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
package xmlDemo
import (
"io/ioutil"
"log"
"strings"
"encoding/xml"
"fmt"
)
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 ParseXML(filename string) {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
reader := strings.NewReader(string(bytes))
parser := xml.NewDecoder(reader)
depth := 0
for {
token, err := parser.Token()
if err != nil {
break
}
switch t := token.(type) {
case xml.StartElement:
elem := xml.StartElement(t)
name := elem.Name.Local
printElem(name, depth)
depth++
case xml.EndElement:
depth--
elem := xml.EndElement(t)
name := elem.Name.Local
printElem(name, depth)
case xml.CharData:
bytes := xml.CharData(t)
printElem("\""+string([]byte(bytes))+"\"",depth)
case xml.Comment:
printElem("Comment", depth)
case xml.ProcInst:
printElem("ProcInst", depth)
case xml.Directive:
printElem("Directive", depth)
default:
fmt.Println("Unknown")
}
}
}
func UnmarshalXML(filename string){
bytes, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
var person Person
if xml.Unmarshal(bytes,&person) != nil {
log.Fatal(err)
}
fmt.Println("Family name: \"" + person.Name.Family + "\"")
fmt.Println("Second email address: \"" + person.Email[1].Address + "\"")
}
func printElem(str string,depth int){
for n:=0;n<depth;n++{
fmt.Print(" ")
}
fmt.Println(str)
}