1 // Copyright 2011 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.
19 // Header is a generic XML header suitable for use with the output of Marshal.
20 // This is not automatically added to any output of this package,
21 // it is provided as a convenience.
22 Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
25 // Marshal returns the XML encoding of v.
27 // Marshal handles an array or slice by marshaling each of the elements.
28 // Marshal handles a pointer by marshaling the value it points at or, if the
29 // pointer is nil, by writing nothing. Marshal handles an interface value by
30 // marshaling the value it contains or, if the interface value is nil, by
31 // writing nothing. Marshal handles all other data by writing one or more XML
32 // elements containing the data.
34 // The name for the XML elements is taken from, in order of preference:
35 // - the tag on the XMLName field, if the data is a struct
36 // - the value of the XMLName field of type Name
37 // - the tag of the struct field used to obtain the data
38 // - the name of the struct field used to obtain the data
39 // - the name of the marshaled type
41 // The XML element for a struct contains marshaled elements for each of the
42 // exported fields of the struct, with these exceptions:
43 // - the XMLName field, described above, is omitted.
44 // - a field with tag "-" is omitted.
45 // - a field with tag "name,attr" becomes an attribute with
46 // the given name in the XML element.
47 // - a field with tag ",attr" becomes an attribute with the
48 // field name in the XML element.
49 // - a field with tag ",chardata" is written as character data,
50 // not as an XML element.
51 // - a field with tag ",cdata" is written as character data
52 // wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element.
53 // - a field with tag ",innerxml" is written verbatim, not subject
54 // to the usual marshaling procedure.
55 // - a field with tag ",comment" is written as an XML comment, not
56 // subject to the usual marshaling procedure. It must not contain
57 // the "--" string within it.
58 // - a field with a tag including the "omitempty" option is omitted
59 // if the field value is empty. The empty values are false, 0, any
60 // nil pointer or interface value, and any array, slice, map, or
61 // string of length zero.
62 // - an anonymous struct field is handled as if the fields of its
63 // value were part of the outer struct.
64 // - a field implementing Marshaler is written by calling its MarshalXML
66 // - a field implementing encoding.TextMarshaler is written by encoding the
67 // result of its MarshalText method as text.
69 // If a field uses a tag "a>b>c", then the element c will be nested inside
70 // parent elements a and b. Fields that appear next to each other that name
71 // the same parent will be enclosed in one XML element.
73 // If the XML name for a struct field is defined by both the field tag and the
74 // struct's XMLName field, the names must match.
76 // See MarshalIndent for an example.
78 // Marshal will return an error if asked to marshal a channel, function, or map.
79 func Marshal(v interface{}) ([]byte, error) {
81 if err := NewEncoder(&b).Encode(v); err != nil {
87 // Marshaler is the interface implemented by objects that can marshal
88 // themselves into valid XML elements.
90 // MarshalXML encodes the receiver as zero or more XML elements.
91 // By convention, arrays or slices are typically encoded as a sequence
92 // of elements, one per entry.
93 // Using start as the element tag is not required, but doing so
94 // will enable Unmarshal to match the XML elements to the correct
96 // One common implementation strategy is to construct a separate
97 // value with a layout corresponding to the desired XML and then
98 // to encode it using e.EncodeElement.
99 // Another common strategy is to use repeated calls to e.EncodeToken
100 // to generate the XML output one token at a time.
101 // The sequence of encoded tokens must make up zero or more valid
103 type Marshaler interface {
104 MarshalXML(e *Encoder, start StartElement) error
107 // MarshalerAttr is the interface implemented by objects that can marshal
108 // themselves into valid XML attributes.
110 // MarshalXMLAttr returns an XML attribute with the encoded value of the receiver.
111 // Using name as the attribute name is not required, but doing so
112 // will enable Unmarshal to match the attribute to the correct
114 // If MarshalXMLAttr returns the zero attribute Attr{}, no attribute
115 // will be generated in the output.
116 // MarshalXMLAttr is used only for struct fields with the
117 // "attr" option in the field tag.
118 type MarshalerAttr interface {
119 MarshalXMLAttr(name Name) (Attr, error)
122 // MarshalIndent works like Marshal, but each XML element begins on a new
123 // indented line that starts with prefix and is followed by one or more
124 // copies of indent according to the nesting depth.
125 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
127 enc := NewEncoder(&b)
128 enc.Indent(prefix, indent)
129 if err := enc.Encode(v); err != nil {
132 return b.Bytes(), nil
135 // An Encoder writes XML data to an output stream.
136 type Encoder struct {
140 // NewEncoder returns a new encoder that writes to w.
141 func NewEncoder(w io.Writer) *Encoder {
142 e := &Encoder{printer{Writer: bufio.NewWriter(w)}}
147 // Indent sets the encoder to generate XML in which each element
148 // begins on a new indented line that starts with prefix and is followed by
149 // one or more copies of indent according to the nesting depth.
150 func (enc *Encoder) Indent(prefix, indent string) {
151 enc.p.prefix = prefix
152 enc.p.indent = indent
155 // Encode writes the XML encoding of v to the stream.
157 // See the documentation for Marshal for details about the conversion
158 // of Go values to XML.
160 // Encode calls Flush before returning.
161 func (enc *Encoder) Encode(v interface{}) error {
162 err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil)
169 // EncodeElement writes the XML encoding of v to the stream,
170 // using start as the outermost tag in the encoding.
172 // See the documentation for Marshal for details about the conversion
173 // of Go values to XML.
175 // EncodeElement calls Flush before returning.
176 func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error {
177 err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start)
185 begComment = []byte("<!--")
186 endComment = []byte("-->")
187 endProcInst = []byte("?>")
190 // EncodeToken writes the given XML token to the stream.
191 // It returns an error if StartElement and EndElement tokens are not properly matched.
193 // EncodeToken does not call Flush, because usually it is part of a larger operation
194 // such as Encode or EncodeElement (or a custom Marshaler's MarshalXML invoked
195 // during those), and those will call Flush when finished.
196 // Callers that create an Encoder and then invoke EncodeToken directly, without
197 // using Encode or EncodeElement, need to call Flush when finished to ensure
198 // that the XML is written to the underlying writer.
200 // EncodeToken allows writing a ProcInst with Target set to "xml" only as the first token
202 func (enc *Encoder) EncodeToken(t Token) error {
205 switch t := t.(type) {
207 if err := p.writeStart(&t); err != nil {
211 if err := p.writeEnd(t.Name); err != nil {
215 escapeText(p, t, false)
217 if bytes.Contains(t, endComment) {
218 return fmt.Errorf("xml: EncodeToken of Comment containing --> marker")
220 p.WriteString("<!--")
223 return p.cachedWriteError()
225 // First token to be encoded which is also a ProcInst with target of xml
226 // is the xml declaration. The only ProcInst where target of xml is allowed.
227 if t.Target == "xml" && p.Buffered() != 0 {
228 return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded")
230 if !isNameString(t.Target) {
231 return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target")
233 if bytes.Contains(t.Inst, endProcInst) {
234 return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker")
237 p.WriteString(t.Target)
244 if !isValidDirective(t) {
245 return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers")
251 return fmt.Errorf("xml: EncodeToken of invalid token type")
254 return p.cachedWriteError()
257 // isValidDirective reports whether dir is a valid directive text,
258 // meaning angle brackets are matched, ignoring comments and strings.
259 func isValidDirective(dir Directive) bool {
265 for i, c := range dir {
269 if n := 1 + i - len(endComment); n >= 0 && bytes.Equal(dir[n:i+1], endComment) {
273 // Just ignore anything in comment
278 // Just ignore anything within quotes
279 case c == '\'' || c == '"':
282 if i+len(begComment) < len(dir) && bytes.Equal(dir[i:i+len(begComment)], begComment) {
294 return depth == 0 && inquote == 0 && !incomment
297 // Flush flushes any buffered XML to the underlying writer.
298 // See the EncodeToken documentation for details about when it is necessary.
299 func (enc *Encoder) Flush() error {
303 type printer struct {
312 attrNS map[string]string // map prefix -> name space
313 attrPrefix map[string]string // map name space -> prefix
318 // createAttrPrefix finds the name space prefix attribute to use for the given name space,
319 // defining a new prefix if necessary. It returns the prefix.
320 func (p *printer) createAttrPrefix(url string) string {
321 if prefix := p.attrPrefix[url]; prefix != "" {
325 // The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml"
326 // and must be referred to that way.
327 // (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns",
328 // but users should not be trying to use that one directly - that's our job.)
333 // Need to define a new name space.
334 if p.attrPrefix == nil {
335 p.attrPrefix = make(map[string]string)
336 p.attrNS = make(map[string]string)
339 // Pick a name. We try to use the final element of the path
340 // but fall back to _.
341 prefix := strings.TrimRight(url, "/")
342 if i := strings.LastIndex(prefix, "/"); i >= 0 {
343 prefix = prefix[i+1:]
345 if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") {
348 if strings.HasPrefix(prefix, "xml") {
349 // xmlanything is reserved.
350 prefix = "_" + prefix
352 if p.attrNS[prefix] != "" {
353 // Name is taken. Find a better one.
354 for p.seq++; ; p.seq++ {
355 if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" {
362 p.attrPrefix[url] = prefix
363 p.attrNS[prefix] = url
365 p.WriteString(`xmlns:`)
366 p.WriteString(prefix)
368 EscapeText(p, []byte(url))
371 p.prefixes = append(p.prefixes, prefix)
376 // deleteAttrPrefix removes an attribute name space prefix.
377 func (p *printer) deleteAttrPrefix(prefix string) {
378 delete(p.attrPrefix, p.attrNS[prefix])
379 delete(p.attrNS, prefix)
382 func (p *printer) markPrefix() {
383 p.prefixes = append(p.prefixes, "")
386 func (p *printer) popPrefix() {
387 for len(p.prefixes) > 0 {
388 prefix := p.prefixes[len(p.prefixes)-1]
389 p.prefixes = p.prefixes[:len(p.prefixes)-1]
393 p.deleteAttrPrefix(prefix)
398 marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
399 marshalerAttrType = reflect.TypeOf((*MarshalerAttr)(nil)).Elem()
400 textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
403 // marshalValue writes one or more XML elements representing val.
404 // If val was obtained from a struct field, finfo must have its details.
405 func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error {
406 if startTemplate != nil && startTemplate.Name.Local == "" {
407 return fmt.Errorf("xml: EncodeElement of StartElement with missing name")
413 if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) {
417 // Drill into interfaces and pointers.
418 // This can turn into an infinite loop given a cyclic chain,
419 // but it matches the Go 1 behavior.
420 for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr {
430 // Check for marshaler.
431 if val.CanInterface() && typ.Implements(marshalerType) {
432 return p.marshalInterface(val.Interface().(Marshaler), defaultStart(typ, finfo, startTemplate))
436 if pv.CanInterface() && pv.Type().Implements(marshalerType) {
437 return p.marshalInterface(pv.Interface().(Marshaler), defaultStart(pv.Type(), finfo, startTemplate))
441 // Check for text marshaler.
442 if val.CanInterface() && typ.Implements(textMarshalerType) {
443 return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), defaultStart(typ, finfo, startTemplate))
447 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
448 return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), defaultStart(pv.Type(), finfo, startTemplate))
452 // Slices and arrays iterate over the elements. They do not have an enclosing tag.
453 if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 {
454 for i, n := 0, val.Len(); i < n; i++ {
455 if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil {
462 tinfo, err := getTypeInfo(typ)
467 // Create start element.
468 // Precedence for the XML element name is:
470 // 1. XMLName field in underlying struct;
471 // 2. field name/tag in the struct field; and
473 var start StartElement
475 if startTemplate != nil {
476 start.Name = startTemplate.Name
477 start.Attr = append(start.Attr, startTemplate.Attr...)
478 } else if tinfo.xmlname != nil {
479 xmlname := tinfo.xmlname
480 if xmlname.name != "" {
481 start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name
482 } else if v, ok := xmlname.value(val).Interface().(Name); ok && v.Local != "" {
486 if start.Name.Local == "" && finfo != nil {
487 start.Name.Space, start.Name.Local = finfo.xmlns, finfo.name
489 if start.Name.Local == "" {
492 return &UnsupportedTypeError{typ}
494 start.Name.Local = name
498 for i := range tinfo.fields {
499 finfo := &tinfo.fields[i]
500 if finfo.flags&fAttr == 0 {
503 fv := finfo.value(val)
505 if finfo.flags&fOmitEmpty != 0 && isEmptyValue(fv) {
509 if fv.Kind() == reflect.Interface && fv.IsNil() {
513 name := Name{Space: finfo.xmlns, Local: finfo.name}
514 if err := p.marshalAttr(&start, name, fv); err != nil {
519 if err := p.writeStart(&start); err != nil {
523 if val.Kind() == reflect.Struct {
524 err = p.marshalStruct(tinfo, val)
526 s, b, err1 := p.marshalSimple(typ, val)
539 if err := p.writeEnd(start.Name); err != nil {
543 return p.cachedWriteError()
546 // marshalAttr marshals an attribute with the given name and value, adding to start.Attr.
547 func (p *printer) marshalAttr(start *StartElement, name Name, val reflect.Value) error {
548 if val.CanInterface() && val.Type().Implements(marshalerAttrType) {
549 attr, err := val.Interface().(MarshalerAttr).MarshalXMLAttr(name)
553 if attr.Name.Local != "" {
554 start.Attr = append(start.Attr, attr)
561 if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) {
562 attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name)
566 if attr.Name.Local != "" {
567 start.Attr = append(start.Attr, attr)
573 if val.CanInterface() && val.Type().Implements(textMarshalerType) {
574 text, err := val.Interface().(encoding.TextMarshaler).MarshalText()
578 start.Attr = append(start.Attr, Attr{name, string(text)})
584 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
585 text, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
589 start.Attr = append(start.Attr, Attr{name, string(text)})
594 // Dereference or skip nil pointer, interface values.
596 case reflect.Ptr, reflect.Interface:
604 if val.Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
606 for i := 0; i < n; i++ {
607 if err := p.marshalAttr(start, name, val.Index(i)); err != nil {
614 if val.Type() == attrType {
615 start.Attr = append(start.Attr, val.Interface().(Attr))
619 s, b, err := p.marshalSimple(val.Type(), val)
626 start.Attr = append(start.Attr, Attr{name, s})
630 // defaultStart returns the default start element to use,
631 // given the reflect type, field info, and start template.
632 func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement {
633 var start StartElement
634 // Precedence for the XML element name is as above,
635 // except that we do not look inside structs for the first field.
636 if startTemplate != nil {
637 start.Name = startTemplate.Name
638 start.Attr = append(start.Attr, startTemplate.Attr...)
639 } else if finfo != nil && finfo.name != "" {
640 start.Name.Local = finfo.name
641 start.Name.Space = finfo.xmlns
642 } else if typ.Name() != "" {
643 start.Name.Local = typ.Name()
645 // Must be a pointer to a named type,
646 // since it has the Marshaler methods.
647 start.Name.Local = typ.Elem().Name()
652 // marshalInterface marshals a Marshaler interface value.
653 func (p *printer) marshalInterface(val Marshaler, start StartElement) error {
654 // Push a marker onto the tag stack so that MarshalXML
655 // cannot close the XML tags that it did not open.
656 p.tags = append(p.tags, Name{})
659 err := val.MarshalXML(p.encoder, start)
664 // Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark.
666 return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local)
668 p.tags = p.tags[:n-1]
672 // marshalTextInterface marshals a TextMarshaler interface value.
673 func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error {
674 if err := p.writeStart(&start); err != nil {
677 text, err := val.MarshalText()
682 return p.writeEnd(start.Name)
685 // writeStart writes the given start element.
686 func (p *printer) writeStart(start *StartElement) error {
687 if start.Name.Local == "" {
688 return fmt.Errorf("xml: start tag with no name")
691 p.tags = append(p.tags, start.Name)
696 p.WriteString(start.Name.Local)
698 if start.Name.Space != "" {
699 p.WriteString(` xmlns="`)
700 p.EscapeString(start.Name.Space)
705 for _, attr := range start.Attr {
707 if name.Local == "" {
711 if name.Space != "" {
712 p.WriteString(p.createAttrPrefix(name.Space))
715 p.WriteString(name.Local)
717 p.EscapeString(attr.Value)
724 func (p *printer) writeEnd(name Name) error {
725 if name.Local == "" {
726 return fmt.Errorf("xml: end tag with no name")
728 if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" {
729 return fmt.Errorf("xml: end tag </%s> without start tag", name.Local)
731 if top := p.tags[len(p.tags)-1]; top != name {
732 if top.Local != name.Local {
733 return fmt.Errorf("xml: end tag </%s> does not match start tag <%s>", name.Local, top.Local)
735 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)
737 p.tags = p.tags[:len(p.tags)-1]
742 p.WriteString(name.Local)
748 func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) {
750 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
751 return strconv.FormatInt(val.Int(), 10), nil, nil
752 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
753 return strconv.FormatUint(val.Uint(), 10), nil, nil
754 case reflect.Float32, reflect.Float64:
755 return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil
757 return val.String(), nil, nil
759 return strconv.FormatBool(val.Bool()), nil, nil
761 if typ.Elem().Kind() != reflect.Uint8 {
767 bytes = val.Slice(0, val.Len()).Bytes()
769 bytes = make([]byte, val.Len())
770 reflect.Copy(reflect.ValueOf(bytes), val)
772 return "", bytes, nil
774 if typ.Elem().Kind() != reflect.Uint8 {
778 return "", val.Bytes(), nil
780 return "", nil, &UnsupportedTypeError{typ}
783 var ddBytes = []byte("--")
785 // indirect drills into interfaces and pointers, returning the pointed-at value.
786 // If it encounters a nil interface or pointer, indirect returns that nil value.
787 // This can turn into an infinite loop given a cyclic chain,
788 // but it matches the Go 1 behavior.
789 func indirect(vf reflect.Value) reflect.Value {
790 for vf.Kind() == reflect.Interface || vf.Kind() == reflect.Ptr {
799 func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error {
800 s := parentStack{p: p}
801 for i := range tinfo.fields {
802 finfo := &tinfo.fields[i]
803 if finfo.flags&fAttr != 0 {
806 vf := finfo.value(val)
808 switch finfo.flags & fMode {
809 case fCDATA, fCharData:
811 if finfo.flags&fMode == fCDATA {
814 if err := s.trim(finfo.parents); err != nil {
817 if vf.CanInterface() && vf.Type().Implements(textMarshalerType) {
818 data, err := vf.Interface().(encoding.TextMarshaler).MarshalText()
822 if err := emit(p, data); err != nil {
829 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
830 data, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
834 if err := emit(p, data); err != nil {
844 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
845 if err := emit(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)); err != nil {
848 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
849 if err := emit(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)); err != nil {
852 case reflect.Float32, reflect.Float64:
853 if err := emit(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())); err != nil {
857 if err := emit(p, strconv.AppendBool(scratch[:0], vf.Bool())); err != nil {
861 if err := emit(p, []byte(vf.String())); err != nil {
865 if elem, ok := vf.Interface().([]byte); ok {
866 if err := emit(p, elem); err != nil {
874 if err := s.trim(finfo.parents); err != nil {
879 if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) {
880 return fmt.Errorf("xml: bad type for comment field of %s", val.Type())
886 p.WriteString("<!--")
892 dashDash = strings.Contains(s, "--")
893 dashLast = s[len(s)-1] == '-'
899 dashDash = bytes.Contains(b, ddBytes)
900 dashLast = b[len(b)-1] == '-'
905 panic("can't happen")
908 return fmt.Errorf(`xml: comments must not contain "--"`)
911 // "--->" is invalid grammar. Make it "- -->"
919 iface := vf.Interface()
920 switch raw := iface.(type) {
929 case fElement, fElement | fAny:
930 if err := s.trim(finfo.parents); err != nil {
933 if len(finfo.parents) > len(s.stack) {
934 if vf.Kind() != reflect.Ptr && vf.Kind() != reflect.Interface || !vf.IsNil() {
935 if err := s.push(finfo.parents[len(s.stack):]); err != nil {
941 if err := p.marshalValue(vf, finfo, nil); err != nil {
946 return p.cachedWriteError()
949 // return the bufio Writer's cached write error
950 func (p *printer) cachedWriteError() error {
951 _, err := p.Write(nil)
955 func (p *printer) writeIndent(depthDelta int) {
956 if len(p.prefix) == 0 && len(p.indent) == 0 {
972 if len(p.prefix) > 0 {
973 p.WriteString(p.prefix)
975 if len(p.indent) > 0 {
976 for i := 0; i < p.depth; i++ {
977 p.WriteString(p.indent)
986 type parentStack struct {
991 // trim updates the XML context to match the longest common prefix of the stack
992 // and the given parents. A closing tag will be written for every parent
993 // popped. Passing a zero slice or nil will close all the elements.
994 func (s *parentStack) trim(parents []string) error {
996 for ; split < len(parents) && split < len(s.stack); split++ {
997 if parents[split] != s.stack[split] {
1001 for i := len(s.stack) - 1; i >= split; i-- {
1002 if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil {
1006 s.stack = s.stack[:split]
1010 // push adds parent elements to the stack and writes open tags.
1011 func (s *parentStack) push(parents []string) error {
1012 for i := 0; i < len(parents); i++ {
1013 if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil {
1017 s.stack = append(s.stack, parents...)
1021 // UnsupportedTypeError is returned when Marshal encounters a type
1022 // that cannot be converted into XML.
1023 type UnsupportedTypeError struct {
1027 func (e *UnsupportedTypeError) Error() string {
1028 return "xml: unsupported type: " + e.Type.String()
1031 func isEmptyValue(v reflect.Value) bool {
1033 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
1037 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1039 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1040 return v.Uint() == 0
1041 case reflect.Float32, reflect.Float64:
1042 return v.Float() == 0
1043 case reflect.Interface, reflect.Ptr: