-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathxml_test.go
87 lines (64 loc) · 2.06 KB
/
xml_test.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
package skill
import (
"encoding/xml"
"fmt"
"testing"
)
type Plant struct {
XMLName xml.Name `xml:"plant"`
ID int `xml:"id,attr"`
Name string `xml:"name"`
Origin []string `xml:"origin"`
}
func TestXmlFunction(t *testing.T) {
coffee := &Plant{ID: 27, Name: "Coffee"}
coffee.Origin = []string{"Ethiopia", "Brazil"}
out, _ := xml.Marshal(coffee)
t.Log(string(out))
assertEq([]byte(`<plant id="27"><name>Coffee</name><origin>Ethiopia</origin><origin>Brazil</origin></plant>`), out)
t.Log(xml.Header + string(out))
assertEq(`<?xml version="1.0" encoding="UTF-8"?>`+"\n", xml.Header)
var p Plant
if err := xml.Unmarshal(out, &p); err != nil {
panic(err)
}
t.Log(p)
assertEq("Coffee", p.Name)
assertEq(27, p.ID)
tomato := &Plant{ID: 81, Name: "Tomato"}
tomato.Origin = []string{"Mexico", "California"}
type Nesting struct {
XMLName xml.Name `xml:"nesting"`
Plants []*Plant `xml:"parent>child>plant"`
}
nesting := &Nesting{}
nesting.Plants = []*Plant{coffee, tomato}
out, _ = xml.Marshal(nesting)
assertEq(`<nesting><parent><child><plant id="27"><name>Coffee</name><origin>Ethiopia</origin><origin>Brazil</origin></plant><plant id="81"><name>Tomato</name><origin>Mexico</origin><origin>California</origin></plant></child></parent></nesting>`, string(out))
//xmlFunction()
}
func (p Plant) String() string {
return fmt.Sprintf("Plant id=%v, name=%v, origin=%v", p.ID, p.Name, p.Origin)
}
func xmlFunction() {
coffee := &Plant{ID: 27, Name: "Coffee"}
coffee.Origin = []string{"Ethiopia", "Brazil"}
out, _ := xml.MarshalIndent(coffee, " ", " ")
fmt.Println(string(out))
fmt.Println(xml.Header + string(out))
var p Plant
if err := xml.Unmarshal(out, &p); err != nil {
panic(err)
}
fmt.Println(p)
tomato := &Plant{ID: 81, Name: "Tomato"}
tomato.Origin = []string{"Mexico", "California"}
type Nesting struct {
XMLName xml.Name `xml:"nesting"`
Plants []*Plant `xml:"parent>child>plant"`
}
nesting := &Nesting{}
nesting.Plants = []*Plant{coffee, tomato}
out, _ = xml.MarshalIndent(nesting, " ", " ")
fmt.Println(string(out))
}