2
3
5
package xml_test
7
import (
8
"encoding/xml"
9
"fmt"
10
"os"
11
)
13
func ExampleMarshalIndent() {
14
type Address struct {
15
City, State string
16
}
17
type Person struct {
18
XMLName xml.Name `xml:"person"`
19
Id int `xml:"id,attr"`
20
FirstName string `xml:"name>first"`
21
LastName string `xml:"name>last"`
22
Age int `xml:"age"`
23
Height float32 `xml:"height,omitempty"`
24
Married bool
25
Address
26
Comment string `xml:",comment"`
27
}
29
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
30
v.Comment = " Need more details. "
31
v.Address = Address{"Hanga Roa", "Easter Island"}
33
output, err := xml.MarshalIndent(v, " ", " ")
34
if err != nil {
35
fmt.Printf("error: %v\n", err)
36
}
38
os.Stdout.Write(output)
39
40
41
42
43
44
45
46
47
48
49
50
51
}
53
func ExampleEncoder() {
54
type Address struct {
55
City, State string
56
}
57
type Person struct {
58
XMLName xml.Name `xml:"person"`
59
Id int `xml:"id,attr"`
60
FirstName string `xml:"name>first"`
61
LastName string `xml:"name>last"`
62
Age int `xml:"age"`
63
Height float32 `xml:"height,omitempty"`
64
Married bool
65
Address
66
Comment string `xml:",comment"`
67
}
69
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
70
v.Comment = " Need more details. "
71
v.Address = Address{"Hanga Roa", "Easter Island"}
73
enc := xml.NewEncoder(os.Stdout)
74
enc.Indent(" ", " ")
75
if err := enc.Encode(v); err != nil {
76
fmt.Printf("error: %v\n", err)
77
}
79
80
81
82
83
84
85
86
87
88
89
90
91
}
93
94
95
96
97
func ExampleUnmarshal() {
98
type Email struct {
99
Where string `xml:"where,attr"`
100
Addr string
101
}
102
type Address struct {
103
City, State string
104
}
105
type Result struct {
106
XMLName xml.Name `xml:"Person"`
107
Name string `xml:"FullName"`
108
Phone string
109
Email []Email
110
Groups []string `xml:"Group>Value"`
111
Address
112
}
113
v := Result{Name: "none", Phone: "none"}
115
data := `
116
<Person>
117
<FullName>Grace R. Emlin</FullName>
118
<Company>Example Inc.</Company>
119
<Email where="home">
120
<Addr>
[email protected]</Addr>
121
</Email>
122
<Email where='work'>
123
<Addr>
[email protected]</Addr>
124
</Email>
125
<Group>
126
<Value>Friends</Value>
127
<Value>Squash</Value>
128
</Group>
129
<City>Hanga Roa</City>
130
<State>Easter Island</State>
131
</Person>
132
`
133
err := xml.Unmarshal([]byte(data), &v)
134
if err != nil {
135
fmt.Printf("error: %v", err)
136
return
137
}
138
fmt.Printf("XMLName: %#v\n", v.XMLName)
139
fmt.Printf("Name: %q\n", v.Name)
140
fmt.Printf("Phone: %q\n", v.Phone)
141
fmt.Printf("Email: %v\n", v.Email)
142
fmt.Printf("Groups: %v\n", v.Groups)
143
fmt.Printf("Address: %v\n", v.Address)
144
145
146
147
148
149
150
151
}
View as plain text