1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 func ExampleMarshalIndent() {
18 XMLName xml.Name `xml:"person"`
19 Id int `xml:"id,attr"`
20 FirstName string `xml:"name>first"`
21 LastName string `xml:"name>last"`
23 Height float32 `xml:"height,omitempty"`
26 Comment string `xml:",comment"`
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, " ", " ")
35 fmt.Printf("error: %v\n", err)
38 os.Stdout.Write(output)
42 // <first>John</first>
46 // <Married>false</Married>
47 // <City>Hanga Roa</City>
48 // <State>Easter Island</State>
49 // <!-- Need more details. -->
53 func ExampleEncoder() {
58 XMLName xml.Name `xml:"person"`
59 Id int `xml:"id,attr"`
60 FirstName string `xml:"name>first"`
61 LastName string `xml:"name>last"`
63 Height float32 `xml:"height,omitempty"`
66 Comment string `xml:",comment"`
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)
75 if err := enc.Encode(v); err != nil {
76 fmt.Printf("error: %v\n", err)
82 // <first>John</first>
86 // <Married>false</Married>
87 // <City>Hanga Roa</City>
88 // <State>Easter Island</State>
89 // <!-- Need more details. -->
93 // This example demonstrates unmarshaling an XML excerpt into a value with
94 // some preset fields. Note that the Phone field isn't modified and that
95 // the XML <Company> element is ignored. Also, the Groups field is assigned
96 // considering the element path provided in its tag.
97 func ExampleUnmarshal() {
99 Where string `xml:"where,attr"`
102 type Address struct {
106 XMLName xml.Name `xml:"Person"`
107 Name string `xml:"FullName"`
110 Groups []string `xml:"Group>Value"`
113 v := Result{Name: "none", Phone: "none"}
117 <FullName>Grace R. Emlin</FullName>
118 <Company>Example Inc.</Company>
120 <Addr>gre@example.com</Addr>
123 <Addr>gre@work.com</Addr>
126 <Value>Friends</Value>
127 <Value>Squash</Value>
129 <City>Hanga Roa</City>
130 <State>Easter Island</State>
133 err := xml.Unmarshal([]byte(data), &v)
135 fmt.Printf("error: %v", err)
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)
145 // XMLName: xml.Name{Space:"", Local:"Person"}
146 // Name: "Grace R. Emlin"
148 // Email: [{home gre@example.com} {work gre@work.com}]
149 // Groups: [Friends Squash]
150 // Address: {Hanga Roa Easter Island}