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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
|
<h1> Package xml </h1> <ul id="short-nav">
<li><code>import "encoding/xml"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul> <h2 id="pkg-overview">Overview </h2> <p>Package xml implements a simple XML 1.0 parser that understands XML name spaces. </p> <h4 id="example__customMarshalXML"> <span class="text">Example (CustomMarshalXML)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">package xml_test
import (
"encoding/xml"
"fmt"
"log"
"strings"
)
type Animal int
const (
Unknown Animal = iota
Gopher
Zebra
)
func (a *Animal) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var s string
if err := d.DecodeElement(&s, &start); err != nil {
return err
}
switch strings.ToLower(s) {
default:
*a = Unknown
case "gopher":
*a = Gopher
case "zebra":
*a = Zebra
}
return nil
}
func (a Animal) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
var s string
switch a {
default:
s = "unknown"
case Gopher:
s = "gopher"
case Zebra:
s = "zebra"
}
return e.EncodeElement(s, start)
}
func Example_customMarshalXML() {
blob := `
<animals>
<animal>gopher</animal>
<animal>armadillo</animal>
<animal>zebra</animal>
<animal>unknown</animal>
<animal>gopher</animal>
<animal>bee</animal>
<animal>gopher</animal>
<animal>zebra</animal>
</animals>`
var zoo struct {
Animals []Animal `xml:"animal"`
}
if err := xml.Unmarshal([]byte(blob), &zoo); err != nil {
log.Fatal(err)
}
census := make(map[Animal]int)
for _, animal := range zoo.Animals {
census[animal] += 1
}
fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras: %d\n* Unknown: %d\n",
census[Gopher], census[Zebra], census[Unknown])
// Output:
// Zoo Census:
// * Gophers: 3
// * Zebras: 2
// * Unknown: 3
}
</pre> <h4 id="example__textMarshalXML"> <span class="text">Example (TextMarshalXML)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">package xml_test
import (
"encoding/xml"
"fmt"
"log"
"strings"
)
type Size int
const (
Unrecognized Size = iota
Small
Large
)
func (s *Size) UnmarshalText(text []byte) error {
switch strings.ToLower(string(text)) {
default:
*s = Unrecognized
case "small":
*s = Small
case "large":
*s = Large
}
return nil
}
func (s Size) MarshalText() ([]byte, error) {
var name string
switch s {
default:
name = "unrecognized"
case Small:
name = "small"
case Large:
name = "large"
}
return []byte(name), nil
}
func Example_textMarshalXML() {
blob := `
<sizes>
<size>small</size>
<size>regular</size>
<size>large</size>
<size>unrecognized</size>
<size>small</size>
<size>normal</size>
<size>small</size>
<size>large</size>
</sizes>`
var inventory struct {
Sizes []Size `xml:"size"`
}
if err := xml.Unmarshal([]byte(blob), &inventory); err != nil {
log.Fatal(err)
}
counts := make(map[Size]int)
for _, size := range inventory.Sizes {
counts[size] += 1
}
fmt.Printf("Inventory Counts:\n* Small: %d\n* Large: %d\n* Unrecognized: %d\n",
counts[Small], counts[Large], counts[Unrecognized])
// Output:
// Inventory Counts:
// * Small: 3
// * Large: 2
// * Unrecognized: 3
}
</pre> <h2 id="pkg-index">Index </h2> <ul id="manual-nav">
<li><a href="#pkg-constants">Constants</a></li>
<li><a href="#pkg-variables">Variables</a></li>
<li><a href="#Escape">func Escape(w io.Writer, s []byte)</a></li>
<li><a href="#EscapeText">func EscapeText(w io.Writer, s []byte) error</a></li>
<li><a href="#Marshal">func Marshal(v any) ([]byte, error)</a></li>
<li><a href="#MarshalIndent">func MarshalIndent(v any, prefix, indent string) ([]byte, error)</a></li>
<li><a href="#Unmarshal">func Unmarshal(data []byte, v any) error</a></li>
<li><a href="#Attr">type Attr</a></li>
<li><a href="#CharData">type CharData</a></li>
<li> <a href="#CharData.Copy">func (c CharData) Copy() CharData</a>
</li>
<li><a href="#Comment">type Comment</a></li>
<li> <a href="#Comment.Copy">func (c Comment) Copy() Comment</a>
</li>
<li><a href="#Decoder">type Decoder</a></li>
<li> <a href="#NewDecoder">func NewDecoder(r io.Reader) *Decoder</a>
</li>
<li> <a href="#NewTokenDecoder">func NewTokenDecoder(t TokenReader) *Decoder</a>
</li>
<li> <a href="#Decoder.Decode">func (d *Decoder) Decode(v any) error</a>
</li>
<li> <a href="#Decoder.DecodeElement">func (d *Decoder) DecodeElement(v any, start *StartElement) error</a>
</li>
<li> <a href="#Decoder.InputOffset">func (d *Decoder) InputOffset() int64</a>
</li>
<li> <a href="#Decoder.InputPos">func (d *Decoder) InputPos() (line, column int)</a>
</li>
<li> <a href="#Decoder.RawToken">func (d *Decoder) RawToken() (Token, error)</a>
</li>
<li> <a href="#Decoder.Skip">func (d *Decoder) Skip() error</a>
</li>
<li> <a href="#Decoder.Token">func (d *Decoder) Token() (Token, error)</a>
</li>
<li><a href="#Directive">type Directive</a></li>
<li> <a href="#Directive.Copy">func (d Directive) Copy() Directive</a>
</li>
<li><a href="#Encoder">type Encoder</a></li>
<li> <a href="#NewEncoder">func NewEncoder(w io.Writer) *Encoder</a>
</li>
<li> <a href="#Encoder.Close">func (enc *Encoder) Close() error</a>
</li>
<li> <a href="#Encoder.Encode">func (enc *Encoder) Encode(v any) error</a>
</li>
<li> <a href="#Encoder.EncodeElement">func (enc *Encoder) EncodeElement(v any, start StartElement) error</a>
</li>
<li> <a href="#Encoder.EncodeToken">func (enc *Encoder) EncodeToken(t Token) error</a>
</li>
<li> <a href="#Encoder.Flush">func (enc *Encoder) Flush() error</a>
</li>
<li> <a href="#Encoder.Indent">func (enc *Encoder) Indent(prefix, indent string)</a>
</li>
<li><a href="#EndElement">type EndElement</a></li>
<li><a href="#Marshaler">type Marshaler</a></li>
<li><a href="#MarshalerAttr">type MarshalerAttr</a></li>
<li><a href="#Name">type Name</a></li>
<li><a href="#ProcInst">type ProcInst</a></li>
<li> <a href="#ProcInst.Copy">func (p ProcInst) Copy() ProcInst</a>
</li>
<li><a href="#StartElement">type StartElement</a></li>
<li> <a href="#StartElement.Copy">func (e StartElement) Copy() StartElement</a>
</li>
<li> <a href="#StartElement.End">func (e StartElement) End() EndElement</a>
</li>
<li><a href="#SyntaxError">type SyntaxError</a></li>
<li> <a href="#SyntaxError.Error">func (e *SyntaxError) Error() string</a>
</li>
<li><a href="#TagPathError">type TagPathError</a></li>
<li> <a href="#TagPathError.Error">func (e *TagPathError) Error() string</a>
</li>
<li><a href="#Token">type Token</a></li>
<li> <a href="#CopyToken">func CopyToken(t Token) Token</a>
</li>
<li><a href="#TokenReader">type TokenReader</a></li>
<li><a href="#UnmarshalError">type UnmarshalError</a></li>
<li> <a href="#UnmarshalError.Error">func (e UnmarshalError) Error() string</a>
</li>
<li><a href="#Unmarshaler">type Unmarshaler</a></li>
<li><a href="#UnmarshalerAttr">type UnmarshalerAttr</a></li>
<li><a href="#UnsupportedTypeError">type UnsupportedTypeError</a></li>
<li> <a href="#UnsupportedTypeError.Error">func (e *UnsupportedTypeError) Error() string</a>
</li>
<li><a href="#pkg-note-BUG">Bugs</a></li>
</ul> <div id="pkg-examples"> <h3>Examples</h3> <dl> <dd><a class="exampleLink" href="#example_Encoder">Encoder</a></dd> <dd><a class="exampleLink" href="#example_MarshalIndent">MarshalIndent</a></dd> <dd><a class="exampleLink" href="#example_Unmarshal">Unmarshal</a></dd> <dd><a class="exampleLink" href="#example__customMarshalXML">Package (CustomMarshalXML)</a></dd> <dd><a class="exampleLink" href="#example__textMarshalXML">Package (TextMarshalXML)</a></dd> </dl> </div> <h3>Package files</h3> <p> <span>marshal.go</span> <span>read.go</span> <span>typeinfo.go</span> <span>xml.go</span> </p> <h2 id="pkg-constants">Constants</h2> <pre data-language="go">const (
// Header is a generic XML header suitable for use with the output of [Marshal].
// This is not automatically added to any output of this package,
// it is provided as a convenience.
Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
)</pre> <h2 id="pkg-variables">Variables</h2> <p>HTMLAutoClose is the set of HTML elements that should be considered to close automatically. </p>
<p>See the [Decoder.Strict] and [Decoder.Entity] fields' documentation. </p>
<pre data-language="go">var HTMLAutoClose []string = htmlAutoClose</pre> <p>HTMLEntity is an entity map containing translations for the standard HTML entity characters. </p>
<p>See the [Decoder.Strict] and [Decoder.Entity] fields' documentation. </p>
<pre data-language="go">var HTMLEntity map[string]string = htmlEntity</pre> <h2 id="Escape">func <span>Escape</span> </h2> <pre data-language="go">func Escape(w io.Writer, s []byte)</pre> <p>Escape is like <a href="#EscapeText">EscapeText</a> but omits the error return value. It is provided for backwards compatibility with Go 1.0. Code targeting Go 1.1 or later should use <a href="#EscapeText">EscapeText</a>. </p>
<h2 id="EscapeText">func <span>EscapeText</span> <span title="Added in Go 1.1">1.1</span> </h2> <pre data-language="go">func EscapeText(w io.Writer, s []byte) error</pre> <p>EscapeText writes to w the properly escaped XML equivalent of the plain text data s. </p>
<h2 id="Marshal">func <span>Marshal</span> </h2> <pre data-language="go">func Marshal(v any) ([]byte, error)</pre> <p>Marshal returns the XML encoding of v. </p>
<p>Marshal handles an array or slice by marshaling each of the elements. Marshal handles a pointer by marshaling the value it points at or, if the pointer is nil, by writing nothing. Marshal handles an interface value by marshaling the value it contains or, if the interface value is nil, by writing nothing. Marshal handles all other data by writing one or more XML elements containing the data. </p>
<p>The name for the XML elements is taken from, in order of preference: </p>
<ul> <li>the tag on the XMLName field, if the data is a struct </li>
<li>the value of the XMLName field of type <a href="#Name">Name</a> </li>
<li>the tag of the struct field used to obtain the data </li>
<li>the name of the struct field used to obtain the data </li>
<li>the name of the marshaled type </li>
</ul> <p>The XML element for a struct contains marshaled elements for each of the exported fields of the struct, with these exceptions: </p>
<ul> <li>the XMLName field, described above, is omitted. </li>
<li>a field with tag "-" is omitted. </li>
<li>a field with tag "name,attr" becomes an attribute with the given name in the XML element. </li>
<li>a field with tag ",attr" becomes an attribute with the field name in the XML element. </li>
<li>a field with tag ",chardata" is written as character data, not as an XML element. </li>
<li>a field with tag ",cdata" is written as character data wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element. </li>
<li>a field with tag ",innerxml" is written verbatim, not subject to the usual marshaling procedure. </li>
<li>a field with tag ",comment" is written as an XML comment, not subject to the usual marshaling procedure. It must not contain the "--" string within it. </li>
<li>a field with a tag including the "omitempty" option is omitted if the field value is empty. The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. </li>
<li>an anonymous struct field is handled as if the fields of its value were part of the outer struct. </li>
<li>a field implementing <a href="#Marshaler">Marshaler</a> is written by calling its MarshalXML method. </li>
<li>a field implementing <span>encoding.TextMarshaler</span> is written by encoding the result of its MarshalText method as text. </li>
</ul> <p>If a field uses a tag "a>b>c", then the element c will be nested inside parent elements a and b. Fields that appear next to each other that name the same parent will be enclosed in one XML element. </p>
<p>If the XML name for a struct field is defined by both the field tag and the struct's XMLName field, the names must match. </p>
<p>See <a href="#MarshalIndent">MarshalIndent</a> for an example. </p>
<p>Marshal will return an error if asked to marshal a channel, function, or map. </p>
<h2 id="MarshalIndent">func <span>MarshalIndent</span> </h2> <pre data-language="go">func MarshalIndent(v any, prefix, indent string) ([]byte, error)</pre> <p>MarshalIndent works like <a href="#Marshal">Marshal</a>, but each XML element begins on a new indented line that starts with prefix and is followed by one or more copies of indent according to the nesting depth. </p> <h4 id="example_MarshalIndent"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">type Address struct {
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
}
os.Stdout.Write(output)
</pre> <p>Output:</p> <pre class="output" data-language="go"> <person id="13">
<name>
<first>John</first>
<last>Doe</last>
</name>
<age>42</age>
<Married>false</Married>
<City>Hanga Roa</City>
<State>Easter Island</State>
<!-- Need more details. -->
</person>
</pre> <h2 id="Unmarshal">func <span>Unmarshal</span> </h2> <pre data-language="go">func Unmarshal(data []byte, v any) error</pre> <p>Unmarshal parses the XML-encoded data and stores the result in the value pointed to by v, which must be an arbitrary struct, slice, or string. Well-formed data that does not fit into v is discarded. </p>
<p>Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields. Unmarshal uses a case-sensitive comparison to match XML element names to tag values and struct field names. </p>
<p>Unmarshal maps an XML element to a struct using the following rules. In the rules, the tag of a field refers to the value associated with the key 'xml' in the struct field's tag (see the example above). </p>
<ul> <li><p>If the struct has a field of type []byte or string with tag ",innerxml", Unmarshal accumulates the raw XML nested inside the element in that field. The rest of the rules still apply. </p></li>
<li><p>If the struct has a field named XMLName of type Name, Unmarshal records the element name in that field. </p></li>
<li><p>If the XMLName field has an associated tag of the form "name" or "namespace-URL name", the XML element must have the given name (and, optionally, name space) or else Unmarshal returns an error. </p></li>
<li><p>If the XML element has an attribute whose name matches a struct field name with an associated tag containing ",attr" or the explicit name in a struct field tag of the form "name,attr", Unmarshal records the attribute value in that field. </p></li>
<li><p>If the XML element has an attribute not handled by the previous rule and the struct has a field with an associated tag containing ",any,attr", Unmarshal records the attribute value in the first such field. </p></li>
<li><p>If the XML element contains character data, that data is accumulated in the first struct field that has tag ",chardata". The struct field may have type []byte or string. If there is no such field, the character data is discarded. </p></li>
<li><p>If the XML element contains comments, they are accumulated in the first struct field that has tag ",comment". The struct field may have type []byte or string. If there is no such field, the comments are discarded. </p></li>
<li><p>If the XML element contains a sub-element whose name matches the prefix of a tag formatted as "a" or "a>b>c", unmarshal will descend into the XML structure looking for elements with the given names, and will map the innermost elements to that struct field. A tag starting with ">" is equivalent to one starting with the field name followed by ">". </p></li>
<li><p>If the XML element contains a sub-element whose name matches a struct field's XMLName tag and the struct field has no explicit name tag as per the previous rule, unmarshal maps the sub-element to that struct field. </p></li>
<li><p>If the XML element contains a sub-element whose name matches a field without any mode flags (",attr", ",chardata", etc), Unmarshal maps the sub-element to that struct field. </p></li>
<li><p>If the XML element contains a sub-element that hasn't matched any of the above rules and the struct has a field with tag ",any", unmarshal maps the sub-element to that struct field. </p></li>
<li><p>An anonymous struct field is handled as if the fields of its value were part of the outer struct. </p></li>
<li><p>A struct field with tag "-" is never unmarshaled into. </p></li>
</ul> <p>If Unmarshal encounters a field type that implements the Unmarshaler interface, Unmarshal calls its UnmarshalXML method to produce the value from the XML element. Otherwise, if the value implements <span>encoding.TextUnmarshaler</span>, Unmarshal calls that value's UnmarshalText method. </p>
<p>Unmarshal maps an XML element to a string or []byte by saving the concatenation of that element's character data in the string or []byte. The saved []byte is never nil. </p>
<p>Unmarshal maps an attribute value to a string or []byte by saving the value in the string or slice. </p>
<p>Unmarshal maps an attribute value to an <a href="#Attr">Attr</a> by saving the attribute, including its name, in the Attr. </p>
<p>Unmarshal maps an XML element or attribute value to a slice by extending the length of the slice and mapping the element or attribute to the newly created value. </p>
<p>Unmarshal maps an XML element or attribute value to a bool by setting it to the boolean value represented by the string. Whitespace is trimmed and ignored. </p>
<p>Unmarshal maps an XML element or attribute value to an integer or floating-point field by setting the field to the result of interpreting the string value in decimal. There is no check for overflow. Whitespace is trimmed and ignored. </p>
<p>Unmarshal maps an XML element to a Name by recording the element name. </p>
<p>Unmarshal maps an XML element to a pointer by setting the pointer to a freshly allocated value and then mapping the element to that value. </p>
<p>A missing element or empty attribute value will be unmarshaled as a zero value. If the field is a slice, a zero value will be appended to the field. Otherwise, the field will be set to its zero value. </p> <h4 id="example_Unmarshal"> <span class="text">Example</span>
</h4> <p>This example demonstrates unmarshaling an XML excerpt into a value with some preset fields. Note that the Phone field isn't modified and that the XML <Company> element is ignored. Also, the Groups field is assigned considering the element path provided in its tag. </p> <p>Code:</p> <pre class="code" data-language="go">type Email struct {
Where string `xml:"where,attr"`
Addr string
}
type Address struct {
City, State string
}
type Result struct {
XMLName xml.Name `xml:"Person"`
Name string `xml:"FullName"`
Phone string
Email []Email
Groups []string `xml:"Group>Value"`
Address
}
v := Result{Name: "none", Phone: "none"}
data := `
<Person>
<FullName>Grace R. Emlin</FullName>
<Company>Example Inc.</Company>
<Email where="home">
<Addr>gre@example.com</Addr>
</Email>
<Email where='work'>
<Addr>gre@work.com</Addr>
</Email>
<Group>
<Value>Friends</Value>
<Value>Squash</Value>
</Group>
<City>Hanga Roa</City>
<State>Easter Island</State>
</Person>
`
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("XMLName: %#v\n", v.XMLName)
fmt.Printf("Name: %q\n", v.Name)
fmt.Printf("Phone: %q\n", v.Phone)
fmt.Printf("Email: %v\n", v.Email)
fmt.Printf("Groups: %v\n", v.Groups)
fmt.Printf("Address: %v\n", v.Address)
</pre> <p>Output:</p> <pre class="output" data-language="go">XMLName: xml.Name{Space:"", Local:"Person"}
Name: "Grace R. Emlin"
Phone: "none"
Email: [{home gre@example.com} {work gre@work.com}]
Groups: [Friends Squash]
Address: {Hanga Roa Easter Island}
</pre> <h2 id="Attr">type <span>Attr</span> </h2> <p>An Attr represents an attribute in an XML element (Name=Value). </p>
<pre data-language="go">type Attr struct {
Name Name
Value string
}
</pre> <h2 id="CharData">type <span>CharData</span> </h2> <p>A CharData represents XML character data (raw text), in which XML escape sequences have been replaced by the characters they represent. </p>
<pre data-language="go">type CharData []byte</pre> <h3 id="CharData.Copy">func (CharData) <span>Copy</span> </h3> <pre data-language="go">func (c CharData) Copy() CharData</pre> <p>Copy creates a new copy of CharData. </p>
<h2 id="Comment">type <span>Comment</span> </h2> <p>A Comment represents an XML comment of the form <!--comment-->. The bytes do not include the <!-- and --> comment markers. </p>
<pre data-language="go">type Comment []byte</pre> <h3 id="Comment.Copy">func (Comment) <span>Copy</span> </h3> <pre data-language="go">func (c Comment) Copy() Comment</pre> <p>Copy creates a new copy of Comment. </p>
<h2 id="Decoder">type <span>Decoder</span> </h2> <p>A Decoder represents an XML parser reading a particular input stream. The parser assumes that its input is encoded in UTF-8. </p>
<pre data-language="go">type Decoder struct {
// Strict defaults to true, enforcing the requirements
// of the XML specification.
// If set to false, the parser allows input containing common
// mistakes:
// * If an element is missing an end tag, the parser invents
// end tags as necessary to keep the return values from Token
// properly balanced.
// * In attribute values and character data, unknown or malformed
// character entities (sequences beginning with &) are left alone.
//
// Setting:
//
// d.Strict = false
// d.AutoClose = xml.HTMLAutoClose
// d.Entity = xml.HTMLEntity
//
// creates a parser that can handle typical HTML.
//
// Strict mode does not enforce the requirements of the XML name spaces TR.
// In particular it does not reject name space tags using undefined prefixes.
// Such tags are recorded with the unknown prefix as the name space URL.
Strict bool
// When Strict == false, AutoClose indicates a set of elements to
// consider closed immediately after they are opened, regardless
// of whether an end element is present.
AutoClose []string
// Entity can be used to map non-standard entity names to string replacements.
// The parser behaves as if these standard mappings are present in the map,
// regardless of the actual map content:
//
// "lt": "<",
// "gt": ">",
// "amp": "&",
// "apos": "'",
// "quot": `"`,
Entity map[string]string
// CharsetReader, if non-nil, defines a function to generate
// charset-conversion readers, converting from the provided
// non-UTF-8 charset into UTF-8. If CharsetReader is nil or
// returns an error, parsing stops with an error. One of the
// CharsetReader's result values must be non-nil.
CharsetReader func(charset string, input io.Reader) (io.Reader, error)
// DefaultSpace sets the default name space used for unadorned tags,
// as if the entire XML stream were wrapped in an element containing
// the attribute xmlns="DefaultSpace".
DefaultSpace string // Go 1.1
// contains filtered or unexported fields
}
</pre> <h3 id="NewDecoder">func <span>NewDecoder</span> </h3> <pre data-language="go">func NewDecoder(r io.Reader) *Decoder</pre> <p>NewDecoder creates a new XML parser reading from r. If r does not implement <span>io.ByteReader</span>, NewDecoder will do its own buffering. </p>
<h3 id="NewTokenDecoder">func <span>NewTokenDecoder</span> <span title="Added in Go 1.10">1.10</span> </h3> <pre data-language="go">func NewTokenDecoder(t TokenReader) *Decoder</pre> <p>NewTokenDecoder creates a new XML parser using an underlying token stream. </p>
<h3 id="Decoder.Decode">func (*Decoder) <span>Decode</span> </h3> <pre data-language="go">func (d *Decoder) Decode(v any) error</pre> <p>Decode works like <a href="#Unmarshal">Unmarshal</a>, except it reads the decoder stream to find the start element. </p>
<h3 id="Decoder.DecodeElement">func (*Decoder) <span>DecodeElement</span> </h3> <pre data-language="go">func (d *Decoder) DecodeElement(v any, start *StartElement) error</pre> <p>DecodeElement works like <a href="#Unmarshal">Unmarshal</a> except that it takes a pointer to the start XML element to decode into v. It is useful when a client reads some raw XML tokens itself but also wants to defer to <a href="#Unmarshal">Unmarshal</a> for some elements. </p>
<h3 id="Decoder.InputOffset">func (*Decoder) <span>InputOffset</span> <span title="Added in Go 1.4">1.4</span> </h3> <pre data-language="go">func (d *Decoder) InputOffset() int64</pre> <p>InputOffset returns the input stream byte offset of the current decoder position. The offset gives the location of the end of the most recently returned token and the beginning of the next token. </p>
<h3 id="Decoder.InputPos">func (*Decoder) <span>InputPos</span> <span title="Added in Go 1.19">1.19</span> </h3> <pre data-language="go">func (d *Decoder) InputPos() (line, column int)</pre> <p>InputPos returns the line of the current decoder position and the 1 based input position of the line. The position gives the location of the end of the most recently returned token. </p>
<h3 id="Decoder.RawToken">func (*Decoder) <span>RawToken</span> </h3> <pre data-language="go">func (d *Decoder) RawToken() (Token, error)</pre> <p>RawToken is like <a href="#Decoder.Token">Decoder.Token</a> but does not verify that start and end elements match and does not translate name space prefixes to their corresponding URLs. </p>
<h3 id="Decoder.Skip">func (*Decoder) <span>Skip</span> </h3> <pre data-language="go">func (d *Decoder) Skip() error</pre> <p>Skip reads tokens until it has consumed the end element matching the most recent start element already consumed, skipping nested structures. It returns nil if it finds an end element matching the start element; otherwise it returns an error describing the problem. </p>
<h3 id="Decoder.Token">func (*Decoder) <span>Token</span> </h3> <pre data-language="go">func (d *Decoder) Token() (Token, error)</pre> <p>Token returns the next XML token in the input stream. At the end of the input stream, Token returns nil, <span>io.EOF</span>. </p>
<p>Slices of bytes in the returned token data refer to the parser's internal buffer and remain valid only until the next call to Token. To acquire a copy of the bytes, call <a href="#CopyToken">CopyToken</a> or the token's Copy method. </p>
<p>Token expands self-closing elements such as <br> into separate start and end elements returned by successive calls. </p>
<p>Token guarantees that the <a href="#StartElement">StartElement</a> and <a href="#EndElement">EndElement</a> tokens it returns are properly nested and matched: if Token encounters an unexpected end element or EOF before all expected end elements, it will return an error. </p>
<p>If [Decoder.CharsetReader] is called and returns an error, the error is wrapped and returned. </p>
<p>Token implements XML name spaces as described by <a href="https://www.w3.org/TR/REC-xml-names/">https://www.w3.org/TR/REC-xml-names/</a>. Each of the <a href="#Name">Name</a> structures contained in the Token has the Space set to the URL identifying its name space when known. If Token encounters an unrecognized name space prefix, it uses the prefix as the Space rather than report an error. </p>
<h2 id="Directive">type <span>Directive</span> </h2> <p>A Directive represents an XML directive of the form <!text>. The bytes do not include the <! and > markers. </p>
<pre data-language="go">type Directive []byte</pre> <h3 id="Directive.Copy">func (Directive) <span>Copy</span> </h3> <pre data-language="go">func (d Directive) Copy() Directive</pre> <p>Copy creates a new copy of Directive. </p>
<h2 id="Encoder">type <span>Encoder</span> </h2> <p>An Encoder writes XML data to an output stream. </p>
<pre data-language="go">type Encoder struct {
// contains filtered or unexported fields
}
</pre> <h4 id="example_Encoder"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">type Address struct {
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
enc := xml.NewEncoder(os.Stdout)
enc.Indent(" ", " ")
if err := enc.Encode(v); err != nil {
fmt.Printf("error: %v\n", err)
}
</pre> <p>Output:</p> <pre class="output" data-language="go"> <person id="13">
<name>
<first>John</first>
<last>Doe</last>
</name>
<age>42</age>
<Married>false</Married>
<City>Hanga Roa</City>
<State>Easter Island</State>
<!-- Need more details. -->
</person>
</pre> <h3 id="NewEncoder">func <span>NewEncoder</span> </h3> <pre data-language="go">func NewEncoder(w io.Writer) *Encoder</pre> <p>NewEncoder returns a new encoder that writes to w. </p>
<h3 id="Encoder.Close">func (*Encoder) <span>Close</span> <span title="Added in Go 1.20">1.20</span> </h3> <pre data-language="go">func (enc *Encoder) Close() error</pre> <p>Close the Encoder, indicating that no more data will be written. It flushes any buffered XML to the underlying writer and returns an error if the written XML is invalid (e.g. by containing unclosed elements). </p>
<h3 id="Encoder.Encode">func (*Encoder) <span>Encode</span> </h3> <pre data-language="go">func (enc *Encoder) Encode(v any) error</pre> <p>Encode writes the XML encoding of v to the stream. </p>
<p>See the documentation for <a href="#Marshal">Marshal</a> for details about the conversion of Go values to XML. </p>
<p>Encode calls <a href="#Encoder.Flush">Encoder.Flush</a> before returning. </p>
<h3 id="Encoder.EncodeElement">func (*Encoder) <span>EncodeElement</span> <span title="Added in Go 1.2">1.2</span> </h3> <pre data-language="go">func (enc *Encoder) EncodeElement(v any, start StartElement) error</pre> <p>EncodeElement writes the XML encoding of v to the stream, using start as the outermost tag in the encoding. </p>
<p>See the documentation for <a href="#Marshal">Marshal</a> for details about the conversion of Go values to XML. </p>
<p>EncodeElement calls <a href="#Encoder.Flush">Encoder.Flush</a> before returning. </p>
<h3 id="Encoder.EncodeToken">func (*Encoder) <span>EncodeToken</span> <span title="Added in Go 1.2">1.2</span> </h3> <pre data-language="go">func (enc *Encoder) EncodeToken(t Token) error</pre> <p>EncodeToken writes the given XML token to the stream. It returns an error if <a href="#StartElement">StartElement</a> and <a href="#EndElement">EndElement</a> tokens are not properly matched. </p>
<p>EncodeToken does not call <a href="#Encoder.Flush">Encoder.Flush</a>, because usually it is part of a larger operation such as <a href="#Encoder.Encode">Encoder.Encode</a> or <a href="#Encoder.EncodeElement">Encoder.EncodeElement</a> (or a custom <a href="#Marshaler">Marshaler</a>'s MarshalXML invoked during those), and those will call Flush when finished. Callers that create an Encoder and then invoke EncodeToken directly, without using Encode or EncodeElement, need to call Flush when finished to ensure that the XML is written to the underlying writer. </p>
<p>EncodeToken allows writing a <a href="#ProcInst">ProcInst</a> with Target set to "xml" only as the first token in the stream. </p>
<h3 id="Encoder.Flush">func (*Encoder) <span>Flush</span> <span title="Added in Go 1.2">1.2</span> </h3> <pre data-language="go">func (enc *Encoder) Flush() error</pre> <p>Flush flushes any buffered XML to the underlying writer. See the <a href="#Encoder.EncodeToken">Encoder.EncodeToken</a> documentation for details about when it is necessary. </p>
<h3 id="Encoder.Indent">func (*Encoder) <span>Indent</span> <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (enc *Encoder) Indent(prefix, indent string)</pre> <p>Indent sets the encoder to generate XML in which each element begins on a new indented line that starts with prefix and is followed by one or more copies of indent according to the nesting depth. </p>
<h2 id="EndElement">type <span>EndElement</span> </h2> <p>An EndElement represents an XML end element. </p>
<pre data-language="go">type EndElement struct {
Name Name
}
</pre> <h2 id="Marshaler">type <span>Marshaler</span> <span title="Added in Go 1.2">1.2</span> </h2> <p>Marshaler is the interface implemented by objects that can marshal themselves into valid XML elements. </p>
<p>MarshalXML encodes the receiver as zero or more XML elements. By convention, arrays or slices are typically encoded as a sequence of elements, one per entry. Using start as the element tag is not required, but doing so will enable <a href="#Unmarshal">Unmarshal</a> to match the XML elements to the correct struct field. One common implementation strategy is to construct a separate value with a layout corresponding to the desired XML and then to encode it using e.EncodeElement. Another common strategy is to use repeated calls to e.EncodeToken to generate the XML output one token at a time. The sequence of encoded tokens must make up zero or more valid XML elements. </p>
<pre data-language="go">type Marshaler interface {
MarshalXML(e *Encoder, start StartElement) error
}</pre> <h2 id="MarshalerAttr">type <span>MarshalerAttr</span> <span title="Added in Go 1.2">1.2</span> </h2> <p>MarshalerAttr is the interface implemented by objects that can marshal themselves into valid XML attributes. </p>
<p>MarshalXMLAttr returns an XML attribute with the encoded value of the receiver. Using name as the attribute name is not required, but doing so will enable <a href="#Unmarshal">Unmarshal</a> to match the attribute to the correct struct field. If MarshalXMLAttr returns the zero attribute <a href="#Attr">Attr</a>{}, no attribute will be generated in the output. MarshalXMLAttr is used only for struct fields with the "attr" option in the field tag. </p>
<pre data-language="go">type MarshalerAttr interface {
MarshalXMLAttr(name Name) (Attr, error)
}</pre> <h2 id="Name">type <span>Name</span> </h2> <p>A Name represents an XML name (Local) annotated with a name space identifier (Space). In tokens returned by <a href="#Decoder.Token">Decoder.Token</a>, the Space identifier is given as a canonical URL, not the short prefix used in the document being parsed. </p>
<pre data-language="go">type Name struct {
Space, Local string
}
</pre> <h2 id="ProcInst">type <span>ProcInst</span> </h2> <p>A ProcInst represents an XML processing instruction of the form <?target inst?> </p>
<pre data-language="go">type ProcInst struct {
Target string
Inst []byte
}
</pre> <h3 id="ProcInst.Copy">func (ProcInst) <span>Copy</span> </h3> <pre data-language="go">func (p ProcInst) Copy() ProcInst</pre> <p>Copy creates a new copy of ProcInst. </p>
<h2 id="StartElement">type <span>StartElement</span> </h2> <p>A StartElement represents an XML start element. </p>
<pre data-language="go">type StartElement struct {
Name Name
Attr []Attr
}
</pre> <h3 id="StartElement.Copy">func (StartElement) <span>Copy</span> </h3> <pre data-language="go">func (e StartElement) Copy() StartElement</pre> <p>Copy creates a new copy of StartElement. </p>
<h3 id="StartElement.End">func (StartElement) <span>End</span> <span title="Added in Go 1.2">1.2</span> </h3> <pre data-language="go">func (e StartElement) End() EndElement</pre> <p>End returns the corresponding XML end element. </p>
<h2 id="SyntaxError">type <span>SyntaxError</span> </h2> <p>A SyntaxError represents a syntax error in the XML input stream. </p>
<pre data-language="go">type SyntaxError struct {
Msg string
Line int
}
</pre> <h3 id="SyntaxError.Error">func (*SyntaxError) <span>Error</span> </h3> <pre data-language="go">func (e *SyntaxError) Error() string</pre> <h2 id="TagPathError">type <span>TagPathError</span> </h2> <p>A TagPathError represents an error in the unmarshaling process caused by the use of field tags with conflicting paths. </p>
<pre data-language="go">type TagPathError struct {
Struct reflect.Type
Field1, Tag1 string
Field2, Tag2 string
}
</pre> <h3 id="TagPathError.Error">func (*TagPathError) <span>Error</span> </h3> <pre data-language="go">func (e *TagPathError) Error() string</pre> <h2 id="Token">type <span>Token</span> </h2> <p>A Token is an interface holding one of the token types: <a href="#StartElement">StartElement</a>, <a href="#EndElement">EndElement</a>, <a href="#CharData">CharData</a>, <a href="#Comment">Comment</a>, <a href="#ProcInst">ProcInst</a>, or <a href="#Directive">Directive</a>. </p>
<pre data-language="go">type Token any</pre> <h3 id="CopyToken">func <span>CopyToken</span> </h3> <pre data-language="go">func CopyToken(t Token) Token</pre> <p>CopyToken returns a copy of a Token. </p>
<h2 id="TokenReader">type <span>TokenReader</span> <span title="Added in Go 1.10">1.10</span> </h2> <p>A TokenReader is anything that can decode a stream of XML tokens, including a <a href="#Decoder">Decoder</a>. </p>
<p>When Token encounters an error or end-of-file condition after successfully reading a token, it returns the token. It may return the (non-nil) error from the same call or return the error (and a nil token) from a subsequent call. An instance of this general case is that a TokenReader returning a non-nil token at the end of the token stream may return either io.EOF or a nil error. The next Read should return nil, <span>io.EOF</span>. </p>
<p>Implementations of Token are discouraged from returning a nil token with a nil error. Callers should treat a return of nil, nil as indicating that nothing happened; in particular it does not indicate EOF. </p>
<pre data-language="go">type TokenReader interface {
Token() (Token, error)
}</pre> <h2 id="UnmarshalError">type <span>UnmarshalError</span> </h2> <p>An UnmarshalError represents an error in the unmarshaling process. </p>
<pre data-language="go">type UnmarshalError string</pre> <h3 id="UnmarshalError.Error">func (UnmarshalError) <span>Error</span> </h3> <pre data-language="go">func (e UnmarshalError) Error() string</pre> <h2 id="Unmarshaler">type <span>Unmarshaler</span> <span title="Added in Go 1.2">1.2</span> </h2> <p>Unmarshaler is the interface implemented by objects that can unmarshal an XML element description of themselves. </p>
<p>UnmarshalXML decodes a single XML element beginning with the given start element. If it returns an error, the outer call to Unmarshal stops and returns that error. UnmarshalXML must consume exactly one XML element. One common implementation strategy is to unmarshal into a separate value with a layout matching the expected XML using d.DecodeElement, and then to copy the data from that value into the receiver. Another common strategy is to use d.Token to process the XML object one token at a time. UnmarshalXML may not use d.RawToken. </p>
<pre data-language="go">type Unmarshaler interface {
UnmarshalXML(d *Decoder, start StartElement) error
}</pre> <h2 id="UnmarshalerAttr">type <span>UnmarshalerAttr</span> <span title="Added in Go 1.2">1.2</span> </h2> <p>UnmarshalerAttr is the interface implemented by objects that can unmarshal an XML attribute description of themselves. </p>
<p>UnmarshalXMLAttr decodes a single XML attribute. If it returns an error, the outer call to <a href="#Unmarshal">Unmarshal</a> stops and returns that error. UnmarshalXMLAttr is used only for struct fields with the "attr" option in the field tag. </p>
<pre data-language="go">type UnmarshalerAttr interface {
UnmarshalXMLAttr(attr Attr) error
}</pre> <h2 id="UnsupportedTypeError">type <span>UnsupportedTypeError</span> </h2> <p>UnsupportedTypeError is returned when <a href="#Marshal">Marshal</a> encounters a type that cannot be converted into XML. </p>
<pre data-language="go">type UnsupportedTypeError struct {
Type reflect.Type
}
</pre> <h3 id="UnsupportedTypeError.Error">func (*UnsupportedTypeError) <span>Error</span> </h3> <pre data-language="go">func (e *UnsupportedTypeError) Error() string</pre> <h2 id="pkg-note-BUG">Bugs</h2> <ul> <li>☞ <p>Mapping between XML elements and data structures is inherently flawed: an XML element is an order-dependent collection of anonymous values, while a data structure is an order-independent collection of named values. See <span>encoding/json</span> for a textual representation more suitable to data structures. </p>
</li> </ul><div class="_attribution">
<p class="_attribution-p">
© Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
<a href="http://golang.org/pkg/encoding/xml/" class="_attribution-link">http://golang.org/pkg/encoding/xml/</a>
</p>
</div>
|