1
2
3
4
5 package xml
6
7 import (
8 "bufio"
9 "bytes"
10 "encoding"
11 "errors"
12 "fmt"
13 "io"
14 "reflect"
15 "strconv"
16 "strings"
17 )
18
19 const (
20
21
22
23 Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
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 func Marshal(v any) ([]byte, error) {
81 var b bytes.Buffer
82 enc := NewEncoder(&b)
83 if err := enc.Encode(v); err != nil {
84 return nil, err
85 }
86 if err := enc.Close(); err != nil {
87 return nil, err
88 }
89 return b.Bytes(), nil
90 }
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108 type Marshaler interface {
109 MarshalXML(e *Encoder, start StartElement) error
110 }
111
112
113
114
115
116
117
118
119
120
121
122
123 type MarshalerAttr interface {
124 MarshalXMLAttr(name Name) (Attr, error)
125 }
126
127
128
129
130 func MarshalIndent(v any, prefix, indent string) ([]byte, error) {
131 var b bytes.Buffer
132 enc := NewEncoder(&b)
133 enc.Indent(prefix, indent)
134 if err := enc.Encode(v); err != nil {
135 return nil, err
136 }
137 if err := enc.Close(); err != nil {
138 return nil, err
139 }
140 return b.Bytes(), nil
141 }
142
143
144 type Encoder struct {
145 p printer
146 }
147
148
149 func NewEncoder(w io.Writer) *Encoder {
150 e := &Encoder{printer{w: bufio.NewWriter(w)}}
151 e.p.encoder = e
152 return e
153 }
154
155
156
157
158 func (enc *Encoder) Indent(prefix, indent string) {
159 enc.p.prefix = prefix
160 enc.p.indent = indent
161 }
162
163
164
165
166
167
168
169 func (enc *Encoder) Encode(v any) error {
170 err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil)
171 if err != nil {
172 return err
173 }
174 return enc.p.w.Flush()
175 }
176
177
178
179
180
181
182
183
184 func (enc *Encoder) EncodeElement(v any, start StartElement) error {
185 err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start)
186 if err != nil {
187 return err
188 }
189 return enc.p.w.Flush()
190 }
191
192 var (
193 begComment = []byte("<!--")
194 endComment = []byte("-->")
195 endProcInst = []byte("?>")
196 )
197
198
199
200
201
202
203
204
205
206
207
208
209
210 func (enc *Encoder) EncodeToken(t Token) error {
211
212 p := &enc.p
213 switch t := t.(type) {
214 case StartElement:
215 if err := p.writeStart(&t); err != nil {
216 return err
217 }
218 case EndElement:
219 if err := p.writeEnd(t.Name); err != nil {
220 return err
221 }
222 case CharData:
223 escapeText(p, t, false)
224 case Comment:
225 if bytes.Contains(t, endComment) {
226 return fmt.Errorf("xml: EncodeToken of Comment containing --> marker")
227 }
228 p.WriteString("<!--")
229 p.Write(t)
230 p.WriteString("-->")
231 return p.cachedWriteError()
232 case ProcInst:
233
234
235 if t.Target == "xml" && p.w.Buffered() != 0 {
236 return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded")
237 }
238 if !isNameString(t.Target) {
239 return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target")
240 }
241 if bytes.Contains(t.Inst, endProcInst) {
242 return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker")
243 }
244 p.WriteString("<?")
245 p.WriteString(t.Target)
246 if len(t.Inst) > 0 {
247 p.WriteByte(' ')
248 p.Write(t.Inst)
249 }
250 p.WriteString("?>")
251 case Directive:
252 if !isValidDirective(t) {
253 return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers")
254 }
255 p.WriteString("<!")
256 p.Write(t)
257 p.WriteString(">")
258 default:
259 return fmt.Errorf("xml: EncodeToken of invalid token type")
260
261 }
262 return p.cachedWriteError()
263 }
264
265
266
267 func isValidDirective(dir Directive) bool {
268 var (
269 depth int
270 inquote uint8
271 incomment bool
272 )
273 for i, c := range dir {
274 switch {
275 case incomment:
276 if c == '>' {
277 if n := 1 + i - len(endComment); n >= 0 && bytes.Equal(dir[n:i+1], endComment) {
278 incomment = false
279 }
280 }
281
282 case inquote != 0:
283 if c == inquote {
284 inquote = 0
285 }
286
287 case c == '\'' || c == '"':
288 inquote = c
289 case c == '<':
290 if i+len(begComment) < len(dir) && bytes.Equal(dir[i:i+len(begComment)], begComment) {
291 incomment = true
292 } else {
293 depth++
294 }
295 case c == '>':
296 if depth == 0 {
297 return false
298 }
299 depth--
300 }
301 }
302 return depth == 0 && inquote == 0 && !incomment
303 }
304
305
306
307 func (enc *Encoder) Flush() error {
308 return enc.p.w.Flush()
309 }
310
311
312
313
314 func (enc *Encoder) Close() error {
315 return enc.p.Close()
316 }
317
318 type printer struct {
319 w *bufio.Writer
320 encoder *Encoder
321 seq int
322 indent string
323 prefix string
324 depth int
325 indentedIn bool
326 putNewline bool
327 attrNS map[string]string
328 attrPrefix map[string]string
329 prefixes []string
330 tags []Name
331 closed bool
332 err error
333 }
334
335
336
337 func (p *printer) createAttrPrefix(url string) string {
338 if prefix := p.attrPrefix[url]; prefix != "" {
339 return prefix
340 }
341
342
343
344
345
346 if url == xmlURL {
347 return xmlPrefix
348 }
349
350
351 if p.attrPrefix == nil {
352 p.attrPrefix = make(map[string]string)
353 p.attrNS = make(map[string]string)
354 }
355
356
357
358 prefix := strings.TrimRight(url, "/")
359 if i := strings.LastIndex(prefix, "/"); i >= 0 {
360 prefix = prefix[i+1:]
361 }
362 if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") {
363 prefix = "_"
364 }
365
366
367
368
369 if len(prefix) >= 3 && strings.EqualFold(prefix[:3], "xml") {
370 prefix = "_" + prefix
371 }
372 if p.attrNS[prefix] != "" {
373
374 for p.seq++; ; p.seq++ {
375 if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" {
376 prefix = id
377 break
378 }
379 }
380 }
381
382 p.attrPrefix[url] = prefix
383 p.attrNS[prefix] = url
384
385 p.WriteString(`xmlns:`)
386 p.WriteString(prefix)
387 p.WriteString(`="`)
388 EscapeText(p, []byte(url))
389 p.WriteString(`" `)
390
391 p.prefixes = append(p.prefixes, prefix)
392
393 return prefix
394 }
395
396
397 func (p *printer) deleteAttrPrefix(prefix string) {
398 delete(p.attrPrefix, p.attrNS[prefix])
399 delete(p.attrNS, prefix)
400 }
401
402 func (p *printer) markPrefix() {
403 p.prefixes = append(p.prefixes, "")
404 }
405
406 func (p *printer) popPrefix() {
407 for len(p.prefixes) > 0 {
408 prefix := p.prefixes[len(p.prefixes)-1]
409 p.prefixes = p.prefixes[:len(p.prefixes)-1]
410 if prefix == "" {
411 break
412 }
413 p.deleteAttrPrefix(prefix)
414 }
415 }
416
417 var (
418 marshalerType = reflect.TypeFor[Marshaler]()
419 marshalerAttrType = reflect.TypeFor[MarshalerAttr]()
420 textMarshalerType = reflect.TypeFor[encoding.TextMarshaler]()
421 )
422
423
424
425 func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error {
426 if startTemplate != nil && startTemplate.Name.Local == "" {
427 return fmt.Errorf("xml: EncodeElement of StartElement with missing name")
428 }
429
430 if !val.IsValid() {
431 return nil
432 }
433 if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) {
434 return nil
435 }
436
437
438
439
440 for val.Kind() == reflect.Interface || val.Kind() == reflect.Pointer {
441 if val.IsNil() {
442 return nil
443 }
444 val = val.Elem()
445 }
446
447 kind := val.Kind()
448 typ := val.Type()
449
450
451 if val.CanInterface() && typ.Implements(marshalerType) {
452 return p.marshalInterface(val.Interface().(Marshaler), defaultStart(typ, finfo, startTemplate))
453 }
454 if val.CanAddr() {
455 pv := val.Addr()
456 if pv.CanInterface() && pv.Type().Implements(marshalerType) {
457 return p.marshalInterface(pv.Interface().(Marshaler), defaultStart(pv.Type(), finfo, startTemplate))
458 }
459 }
460
461
462 if val.CanInterface() && typ.Implements(textMarshalerType) {
463 return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), defaultStart(typ, finfo, startTemplate))
464 }
465 if val.CanAddr() {
466 pv := val.Addr()
467 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
468 return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), defaultStart(pv.Type(), finfo, startTemplate))
469 }
470 }
471
472
473 if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 {
474 for i, n := 0, val.Len(); i < n; i++ {
475 if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil {
476 return err
477 }
478 }
479 return nil
480 }
481
482 tinfo, err := getTypeInfo(typ)
483 if err != nil {
484 return err
485 }
486
487
488
489
490
491
492
493 var start StartElement
494
495 if startTemplate != nil {
496 start.Name = startTemplate.Name
497 start.Attr = append(start.Attr, startTemplate.Attr...)
498 } else if tinfo.xmlname != nil {
499 xmlname := tinfo.xmlname
500 if xmlname.name != "" {
501 start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name
502 } else {
503 fv := xmlname.value(val, dontInitNilPointers)
504 if v, ok := fv.Interface().(Name); ok && v.Local != "" {
505 start.Name = v
506 }
507 }
508 }
509 if start.Name.Local == "" && finfo != nil {
510 start.Name.Space, start.Name.Local = finfo.xmlns, finfo.name
511 }
512 if start.Name.Local == "" {
513 name := typ.Name()
514 if i := strings.IndexByte(name, '['); i >= 0 {
515
516 name = name[:i]
517 }
518 if name == "" {
519 return &UnsupportedTypeError{typ}
520 }
521 start.Name.Local = name
522 }
523
524
525 for i := range tinfo.fields {
526 finfo := &tinfo.fields[i]
527 if finfo.flags&fAttr == 0 {
528 continue
529 }
530 fv := finfo.value(val, dontInitNilPointers)
531
532 if finfo.flags&fOmitEmpty != 0 && (!fv.IsValid() || isEmptyValue(fv)) {
533 continue
534 }
535
536 if fv.Kind() == reflect.Interface && fv.IsNil() {
537 continue
538 }
539
540 name := Name{Space: finfo.xmlns, Local: finfo.name}
541 if err := p.marshalAttr(&start, name, fv); err != nil {
542 return err
543 }
544 }
545
546
547 if tinfo.xmlname != nil && start.Name.Space == "" &&
548 tinfo.xmlname.xmlns == "" && tinfo.xmlname.name == "" &&
549 len(p.tags) != 0 && p.tags[len(p.tags)-1].Space != "" {
550 start.Attr = append(start.Attr, Attr{Name{"", xmlnsPrefix}, ""})
551 }
552 if err := p.writeStart(&start); err != nil {
553 return err
554 }
555
556 if val.Kind() == reflect.Struct {
557 err = p.marshalStruct(tinfo, val)
558 } else {
559 s, b, err1 := p.marshalSimple(typ, val)
560 if err1 != nil {
561 err = err1
562 } else if b != nil {
563 EscapeText(p, b)
564 } else {
565 p.EscapeString(s)
566 }
567 }
568 if err != nil {
569 return err
570 }
571
572 if err := p.writeEnd(start.Name); err != nil {
573 return err
574 }
575
576 return p.cachedWriteError()
577 }
578
579
580 func (p *printer) marshalAttr(start *StartElement, name Name, val reflect.Value) error {
581 if val.CanInterface() && val.Type().Implements(marshalerAttrType) {
582 attr, err := val.Interface().(MarshalerAttr).MarshalXMLAttr(name)
583 if err != nil {
584 return err
585 }
586 if attr.Name.Local != "" {
587 start.Attr = append(start.Attr, attr)
588 }
589 return nil
590 }
591
592 if val.CanAddr() {
593 pv := val.Addr()
594 if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) {
595 attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name)
596 if err != nil {
597 return err
598 }
599 if attr.Name.Local != "" {
600 start.Attr = append(start.Attr, attr)
601 }
602 return nil
603 }
604 }
605
606 if val.CanInterface() && val.Type().Implements(textMarshalerType) {
607 text, err := val.Interface().(encoding.TextMarshaler).MarshalText()
608 if err != nil {
609 return err
610 }
611 start.Attr = append(start.Attr, Attr{name, string(text)})
612 return nil
613 }
614
615 if val.CanAddr() {
616 pv := val.Addr()
617 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
618 text, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
619 if err != nil {
620 return err
621 }
622 start.Attr = append(start.Attr, Attr{name, string(text)})
623 return nil
624 }
625 }
626
627
628 switch val.Kind() {
629 case reflect.Pointer, reflect.Interface:
630 if val.IsNil() {
631 return nil
632 }
633 val = val.Elem()
634 }
635
636
637 if val.Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
638 n := val.Len()
639 for i := 0; i < n; i++ {
640 if err := p.marshalAttr(start, name, val.Index(i)); err != nil {
641 return err
642 }
643 }
644 return nil
645 }
646
647 if val.Type() == attrType {
648 start.Attr = append(start.Attr, val.Interface().(Attr))
649 return nil
650 }
651
652 s, b, err := p.marshalSimple(val.Type(), val)
653 if err != nil {
654 return err
655 }
656 if b != nil {
657 s = string(b)
658 }
659 start.Attr = append(start.Attr, Attr{name, s})
660 return nil
661 }
662
663
664
665 func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement {
666 var start StartElement
667
668
669 if startTemplate != nil {
670 start.Name = startTemplate.Name
671 start.Attr = append(start.Attr, startTemplate.Attr...)
672 } else if finfo != nil && finfo.name != "" {
673 start.Name.Local = finfo.name
674 start.Name.Space = finfo.xmlns
675 } else if typ.Name() != "" {
676 start.Name.Local = typ.Name()
677 } else {
678
679
680 start.Name.Local = typ.Elem().Name()
681 }
682 return start
683 }
684
685
686 func (p *printer) marshalInterface(val Marshaler, start StartElement) error {
687
688
689 p.tags = append(p.tags, Name{})
690 n := len(p.tags)
691
692 err := val.MarshalXML(p.encoder, start)
693 if err != nil {
694 return err
695 }
696
697
698 if len(p.tags) > n {
699 return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local)
700 }
701 p.tags = p.tags[:n-1]
702 return nil
703 }
704
705
706 func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error {
707 if err := p.writeStart(&start); err != nil {
708 return err
709 }
710 text, err := val.MarshalText()
711 if err != nil {
712 return err
713 }
714 EscapeText(p, text)
715 return p.writeEnd(start.Name)
716 }
717
718
719 func (p *printer) writeStart(start *StartElement) error {
720 if start.Name.Local == "" {
721 return fmt.Errorf("xml: start tag with no name")
722 }
723
724 p.tags = append(p.tags, start.Name)
725 p.markPrefix()
726
727 p.writeIndent(1)
728 p.WriteByte('<')
729 p.WriteString(start.Name.Local)
730
731 if start.Name.Space != "" {
732 p.WriteString(` xmlns="`)
733 p.EscapeString(start.Name.Space)
734 p.WriteByte('"')
735 }
736
737
738 for _, attr := range start.Attr {
739 name := attr.Name
740 if name.Local == "" {
741 continue
742 }
743 p.WriteByte(' ')
744 if name.Space != "" {
745 p.WriteString(p.createAttrPrefix(name.Space))
746 p.WriteByte(':')
747 }
748 p.WriteString(name.Local)
749 p.WriteString(`="`)
750 p.EscapeString(attr.Value)
751 p.WriteByte('"')
752 }
753 p.WriteByte('>')
754 return nil
755 }
756
757 func (p *printer) writeEnd(name Name) error {
758 if name.Local == "" {
759 return fmt.Errorf("xml: end tag with no name")
760 }
761 if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" {
762 return fmt.Errorf("xml: end tag </%s> without start tag", name.Local)
763 }
764 if top := p.tags[len(p.tags)-1]; top != name {
765 if top.Local != name.Local {
766 return fmt.Errorf("xml: end tag </%s> does not match start tag <%s>", name.Local, top.Local)
767 }
768 return fmt.Errorf("xml: end tag </%s> in namespace %s does not match start tag <%s> in namespace %s", name.Local, name.Space, top.Local, top.Space)
769 }
770 p.tags = p.tags[:len(p.tags)-1]
771
772 p.writeIndent(-1)
773 p.WriteByte('<')
774 p.WriteByte('/')
775 p.WriteString(name.Local)
776 p.WriteByte('>')
777 p.popPrefix()
778 return nil
779 }
780
781 func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) {
782 switch val.Kind() {
783 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
784 return strconv.FormatInt(val.Int(), 10), nil, nil
785 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
786 return strconv.FormatUint(val.Uint(), 10), nil, nil
787 case reflect.Float32, reflect.Float64:
788 return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil
789 case reflect.String:
790 return val.String(), nil, nil
791 case reflect.Bool:
792 return strconv.FormatBool(val.Bool()), nil, nil
793 case reflect.Array:
794 if typ.Elem().Kind() != reflect.Uint8 {
795 break
796 }
797
798 var bytes []byte
799 if val.CanAddr() {
800 bytes = val.Bytes()
801 } else {
802 bytes = make([]byte, val.Len())
803 reflect.Copy(reflect.ValueOf(bytes), val)
804 }
805 return "", bytes, nil
806 case reflect.Slice:
807 if typ.Elem().Kind() != reflect.Uint8 {
808 break
809 }
810
811 return "", val.Bytes(), nil
812 }
813 return "", nil, &UnsupportedTypeError{typ}
814 }
815
816 var ddBytes = []byte("--")
817
818
819
820
821
822 func indirect(vf reflect.Value) reflect.Value {
823 for vf.Kind() == reflect.Interface || vf.Kind() == reflect.Pointer {
824 if vf.IsNil() {
825 return vf
826 }
827 vf = vf.Elem()
828 }
829 return vf
830 }
831
832 func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error {
833 s := parentStack{p: p}
834 for i := range tinfo.fields {
835 finfo := &tinfo.fields[i]
836 if finfo.flags&fAttr != 0 {
837 continue
838 }
839 vf := finfo.value(val, dontInitNilPointers)
840 if !vf.IsValid() {
841
842
843 continue
844 }
845
846 switch finfo.flags & fMode {
847 case fCDATA, fCharData:
848 emit := EscapeText
849 if finfo.flags&fMode == fCDATA {
850 emit = emitCDATA
851 }
852 if err := s.trim(finfo.parents); err != nil {
853 return err
854 }
855 if vf.CanInterface() && vf.Type().Implements(textMarshalerType) {
856 data, err := vf.Interface().(encoding.TextMarshaler).MarshalText()
857 if err != nil {
858 return err
859 }
860 if err := emit(p, data); err != nil {
861 return err
862 }
863 continue
864 }
865 if vf.CanAddr() {
866 pv := vf.Addr()
867 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
868 data, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
869 if err != nil {
870 return err
871 }
872 if err := emit(p, data); err != nil {
873 return err
874 }
875 continue
876 }
877 }
878
879 var scratch [64]byte
880 vf = indirect(vf)
881 switch vf.Kind() {
882 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
883 if err := emit(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)); err != nil {
884 return err
885 }
886 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
887 if err := emit(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)); err != nil {
888 return err
889 }
890 case reflect.Float32, reflect.Float64:
891 if err := emit(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())); err != nil {
892 return err
893 }
894 case reflect.Bool:
895 if err := emit(p, strconv.AppendBool(scratch[:0], vf.Bool())); err != nil {
896 return err
897 }
898 case reflect.String:
899 if err := emit(p, []byte(vf.String())); err != nil {
900 return err
901 }
902 case reflect.Slice:
903 if elem, ok := vf.Interface().([]byte); ok {
904 if err := emit(p, elem); err != nil {
905 return err
906 }
907 }
908 }
909 continue
910
911 case fComment:
912 if err := s.trim(finfo.parents); err != nil {
913 return err
914 }
915 vf = indirect(vf)
916 k := vf.Kind()
917 if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) {
918 return fmt.Errorf("xml: bad type for comment field of %s", val.Type())
919 }
920 if vf.Len() == 0 {
921 continue
922 }
923 p.writeIndent(0)
924 p.WriteString("<!--")
925 dashDash := false
926 dashLast := false
927 switch k {
928 case reflect.String:
929 s := vf.String()
930 dashDash = strings.Contains(s, "--")
931 dashLast = s[len(s)-1] == '-'
932 if !dashDash {
933 p.WriteString(s)
934 }
935 case reflect.Slice:
936 b := vf.Bytes()
937 dashDash = bytes.Contains(b, ddBytes)
938 dashLast = b[len(b)-1] == '-'
939 if !dashDash {
940 p.Write(b)
941 }
942 default:
943 panic("can't happen")
944 }
945 if dashDash {
946 return fmt.Errorf(`xml: comments must not contain "--"`)
947 }
948 if dashLast {
949
950 p.WriteByte(' ')
951 }
952 p.WriteString("-->")
953 continue
954
955 case fInnerXML:
956 vf = indirect(vf)
957 iface := vf.Interface()
958 switch raw := iface.(type) {
959 case []byte:
960 p.Write(raw)
961 continue
962 case string:
963 p.WriteString(raw)
964 continue
965 }
966
967 case fElement, fElement | fAny:
968 if err := s.trim(finfo.parents); err != nil {
969 return err
970 }
971 if len(finfo.parents) > len(s.stack) {
972 if vf.Kind() != reflect.Pointer && vf.Kind() != reflect.Interface || !vf.IsNil() {
973 if err := s.push(finfo.parents[len(s.stack):]); err != nil {
974 return err
975 }
976 }
977 }
978 }
979 if err := p.marshalValue(vf, finfo, nil); err != nil {
980 return err
981 }
982 }
983 s.trim(nil)
984 return p.cachedWriteError()
985 }
986
987
988 func (p *printer) Write(b []byte) (n int, err error) {
989 if p.closed && p.err == nil {
990 p.err = errors.New("use of closed Encoder")
991 }
992 if p.err == nil {
993 n, p.err = p.w.Write(b)
994 }
995 return n, p.err
996 }
997
998
999 func (p *printer) WriteString(s string) (n int, err error) {
1000 if p.closed && p.err == nil {
1001 p.err = errors.New("use of closed Encoder")
1002 }
1003 if p.err == nil {
1004 n, p.err = p.w.WriteString(s)
1005 }
1006 return n, p.err
1007 }
1008
1009
1010 func (p *printer) WriteByte(c byte) error {
1011 if p.closed && p.err == nil {
1012 p.err = errors.New("use of closed Encoder")
1013 }
1014 if p.err == nil {
1015 p.err = p.w.WriteByte(c)
1016 }
1017 return p.err
1018 }
1019
1020
1021
1022
1023 func (p *printer) Close() error {
1024 if p.closed {
1025 return nil
1026 }
1027 p.closed = true
1028 if err := p.w.Flush(); err != nil {
1029 return err
1030 }
1031 if len(p.tags) > 0 {
1032 return fmt.Errorf("unclosed tag <%s>", p.tags[len(p.tags)-1].Local)
1033 }
1034 return nil
1035 }
1036
1037
1038 func (p *printer) cachedWriteError() error {
1039 _, err := p.Write(nil)
1040 return err
1041 }
1042
1043 func (p *printer) writeIndent(depthDelta int) {
1044 if len(p.prefix) == 0 && len(p.indent) == 0 {
1045 return
1046 }
1047 if depthDelta < 0 {
1048 p.depth--
1049 if p.indentedIn {
1050 p.indentedIn = false
1051 return
1052 }
1053 p.indentedIn = false
1054 }
1055 if p.putNewline {
1056 p.WriteByte('\n')
1057 } else {
1058 p.putNewline = true
1059 }
1060 if len(p.prefix) > 0 {
1061 p.WriteString(p.prefix)
1062 }
1063 if len(p.indent) > 0 {
1064 for i := 0; i < p.depth; i++ {
1065 p.WriteString(p.indent)
1066 }
1067 }
1068 if depthDelta > 0 {
1069 p.depth++
1070 p.indentedIn = true
1071 }
1072 }
1073
1074 type parentStack struct {
1075 p *printer
1076 stack []string
1077 }
1078
1079
1080
1081
1082 func (s *parentStack) trim(parents []string) error {
1083 split := 0
1084 for ; split < len(parents) && split < len(s.stack); split++ {
1085 if parents[split] != s.stack[split] {
1086 break
1087 }
1088 }
1089 for i := len(s.stack) - 1; i >= split; i-- {
1090 if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil {
1091 return err
1092 }
1093 }
1094 s.stack = s.stack[:split]
1095 return nil
1096 }
1097
1098
1099 func (s *parentStack) push(parents []string) error {
1100 for i := 0; i < len(parents); i++ {
1101 if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil {
1102 return err
1103 }
1104 }
1105 s.stack = append(s.stack, parents...)
1106 return nil
1107 }
1108
1109
1110
1111 type UnsupportedTypeError struct {
1112 Type reflect.Type
1113 }
1114
1115 func (e *UnsupportedTypeError) Error() string {
1116 return "xml: unsupported type: " + e.Type.String()
1117 }
1118
1119 func isEmptyValue(v reflect.Value) bool {
1120 switch v.Kind() {
1121 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
1122 return v.Len() == 0
1123 case reflect.Bool,
1124 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
1125 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
1126 reflect.Float32, reflect.Float64,
1127 reflect.Interface, reflect.Pointer:
1128 return v.IsZero()
1129 }
1130 return false
1131 }
1132
View as plain text