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.
4
5package xml
6
7import (
8	"bufio"
9	"bytes"
10	"encoding"
11	"errors"
12	"fmt"
13	"io"
14	"reflect"
15	"strconv"
16	"strings"
17)
18
19const (
20	// Header is a generic XML header suitable for use with the output of [Marshal].
21	// This is not automatically added to any output of this package,
22	// it is provided as a convenience.
23	Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
24)
25
26// Marshal returns the XML encoding of v.
27//
28// Marshal handles an array or slice by marshaling each of the elements.
29// Marshal handles a pointer by marshaling the value it points at or, if the
30// pointer is nil, by writing nothing. Marshal handles an interface value by
31// marshaling the value it contains or, if the interface value is nil, by
32// writing nothing. Marshal handles all other data by writing one or more XML
33// elements containing the data.
34//
35// The name for the XML elements is taken from, in order of preference:
36//   - the tag on the XMLName field, if the data is a struct
37//   - the value of the XMLName field of type [Name]
38//   - the tag of the struct field used to obtain the data
39//   - the name of the struct field used to obtain the data
40//   - the name of the marshaled type
41//
42// The XML element for a struct contains marshaled elements for each of the
43// exported fields of the struct, with these exceptions:
44//   - the XMLName field, described above, is omitted.
45//   - a field with tag "-" is omitted.
46//   - a field with tag "name,attr" becomes an attribute with
47//     the given name in the XML element.
48//   - a field with tag ",attr" becomes an attribute with the
49//     field name in the XML element.
50//   - a field with tag ",chardata" is written as character data,
51//     not as an XML element.
52//   - a field with tag ",cdata" is written as character data
53//     wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element.
54//   - a field with tag ",innerxml" is written verbatim, not subject
55//     to the usual marshaling procedure.
56//   - a field with tag ",comment" is written as an XML comment, not
57//     subject to the usual marshaling procedure. It must not contain
58//     the "--" string within it.
59//   - a field with a tag including the "omitempty" option is omitted
60//     if the field value is empty. The empty values are false, 0, any
61//     nil pointer or interface value, and any array, slice, map, or
62//     string of length zero.
63//   - an anonymous struct field is handled as if the fields of its
64//     value were part of the outer struct.
65//   - a field implementing [Marshaler] is written by calling its MarshalXML
66//     method.
67//   - a field implementing [encoding.TextMarshaler] is written by encoding the
68//     result of its MarshalText method as text.
69//
70// If a field uses a tag "a>b>c", then the element c will be nested inside
71// parent elements a and b. Fields that appear next to each other that name
72// the same parent will be enclosed in one XML element.
73//
74// If the XML name for a struct field is defined by both the field tag and the
75// struct's XMLName field, the names must match.
76//
77// See [MarshalIndent] for an example.
78//
79// Marshal will return an error if asked to marshal a channel, function, or map.
80func 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// Marshaler is the interface implemented by objects that can marshal
93// themselves into valid XML elements.
94//
95// MarshalXML encodes the receiver as zero or more XML elements.
96// By convention, arrays or slices are typically encoded as a sequence
97// of elements, one per entry.
98// Using start as the element tag is not required, but doing so
99// will enable [Unmarshal] to match the XML elements to the correct
100// struct field.
101// One common implementation strategy is to construct a separate
102// value with a layout corresponding to the desired XML and then
103// to encode it using e.EncodeElement.
104// Another common strategy is to use repeated calls to e.EncodeToken
105// to generate the XML output one token at a time.
106// The sequence of encoded tokens must make up zero or more valid
107// XML elements.
108type Marshaler interface {
109	MarshalXML(e *Encoder, start StartElement) error
110}
111
112// MarshalerAttr is the interface implemented by objects that can marshal
113// themselves into valid XML attributes.
114//
115// MarshalXMLAttr returns an XML attribute with the encoded value of the receiver.
116// Using name as the attribute name is not required, but doing so
117// will enable [Unmarshal] to match the attribute to the correct
118// struct field.
119// If MarshalXMLAttr returns the zero attribute [Attr]{}, no attribute
120// will be generated in the output.
121// MarshalXMLAttr is used only for struct fields with the
122// "attr" option in the field tag.
123type MarshalerAttr interface {
124	MarshalXMLAttr(name Name) (Attr, error)
125}
126
127// MarshalIndent works like [Marshal], but each XML element begins on a new
128// indented line that starts with prefix and is followed by one or more
129// copies of indent according to the nesting depth.
130func 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// An Encoder writes XML data to an output stream.
144type Encoder struct {
145	p printer
146}
147
148// NewEncoder returns a new encoder that writes to w.
149func NewEncoder(w io.Writer) *Encoder {
150	e := &Encoder{printer{w: bufio.NewWriter(w)}}
151	e.p.encoder = e
152	return e
153}
154
155// Indent sets the encoder to generate XML in which each element
156// begins on a new indented line that starts with prefix and is followed by
157// one or more copies of indent according to the nesting depth.
158func (enc *Encoder) Indent(prefix, indent string) {
159	enc.p.prefix = prefix
160	enc.p.indent = indent
161}
162
163// Encode writes the XML encoding of v to the stream.
164//
165// See the documentation for [Marshal] for details about the conversion
166// of Go values to XML.
167//
168// Encode calls [Encoder.Flush] before returning.
169func (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// EncodeElement writes the XML encoding of v to the stream,
178// using start as the outermost tag in the encoding.
179//
180// See the documentation for [Marshal] for details about the conversion
181// of Go values to XML.
182//
183// EncodeElement calls [Encoder.Flush] before returning.
184func (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
192var (
193	begComment  = []byte("<!--")
194	endComment  = []byte("-->")
195	endProcInst = []byte("?>")
196)
197
198// EncodeToken writes the given XML token to the stream.
199// It returns an error if [StartElement] and [EndElement] tokens are not properly matched.
200//
201// EncodeToken does not call [Encoder.Flush], because usually it is part of a larger operation
202// such as [Encoder.Encode] or [Encoder.EncodeElement] (or a custom [Marshaler]'s MarshalXML invoked
203// during those), and those will call Flush when finished.
204// Callers that create an Encoder and then invoke EncodeToken directly, without
205// using Encode or EncodeElement, need to call Flush when finished to ensure
206// that the XML is written to the underlying writer.
207//
208// EncodeToken allows writing a [ProcInst] with Target set to "xml" only as the first token
209// in the stream.
210func (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		// First token to be encoded which is also a ProcInst with target of xml
234		// is the xml declaration. The only ProcInst where target of xml is allowed.
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// isValidDirective reports whether dir is a valid directive text,
266// meaning angle brackets are matched, ignoring comments and strings.
267func 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			// Just ignore anything in comment
282		case inquote != 0:
283			if c == inquote {
284				inquote = 0
285			}
286			// Just ignore anything within quotes
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// Flush flushes any buffered XML to the underlying writer.
306// See the [Encoder.EncodeToken] documentation for details about when it is necessary.
307func (enc *Encoder) Flush() error {
308	return enc.p.w.Flush()
309}
310
311// Close the Encoder, indicating that no more data will be written. It flushes
312// any buffered XML to the underlying writer and returns an error if the
313// written XML is invalid (e.g. by containing unclosed elements).
314func (enc *Encoder) Close() error {
315	return enc.p.Close()
316}
317
318type 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 // map prefix -> name space
328	attrPrefix map[string]string // map name space -> prefix
329	prefixes   []string
330	tags       []Name
331	closed     bool
332	err        error
333}
334
335// createAttrPrefix finds the name space prefix attribute to use for the given name space,
336// defining a new prefix if necessary. It returns the prefix.
337func (p *printer) createAttrPrefix(url string) string {
338	if prefix := p.attrPrefix[url]; prefix != "" {
339		return prefix
340	}
341
342	// The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml"
343	// and must be referred to that way.
344	// (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns",
345	// but users should not be trying to use that one directly - that's our job.)
346	if url == xmlURL {
347		return xmlPrefix
348	}
349
350	// Need to define a new name space.
351	if p.attrPrefix == nil {
352		p.attrPrefix = make(map[string]string)
353		p.attrNS = make(map[string]string)
354	}
355
356	// Pick a name. We try to use the final element of the path
357	// but fall back to _.
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	// xmlanything is reserved and any variant of it regardless of
366	// case should be matched, so:
367	//    (('X'|'x') ('M'|'m') ('L'|'l'))
368	// See Section 2.3 of https://www.w3.org/TR/REC-xml/
369	if len(prefix) >= 3 && strings.EqualFold(prefix[:3], "xml") {
370		prefix = "_" + prefix
371	}
372	if p.attrNS[prefix] != "" {
373		// Name is taken. Find a better one.
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// deleteAttrPrefix removes an attribute name space prefix.
397func (p *printer) deleteAttrPrefix(prefix string) {
398	delete(p.attrPrefix, p.attrNS[prefix])
399	delete(p.attrNS, prefix)
400}
401
402func (p *printer) markPrefix() {
403	p.prefixes = append(p.prefixes, "")
404}
405
406func (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
417var (
418	marshalerType     = reflect.TypeFor[Marshaler]()
419	marshalerAttrType = reflect.TypeFor[MarshalerAttr]()
420	textMarshalerType = reflect.TypeFor[encoding.TextMarshaler]()
421)
422
423// marshalValue writes one or more XML elements representing val.
424// If val was obtained from a struct field, finfo must have its details.
425func (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	// Drill into interfaces and pointers.
438	// This can turn into an infinite loop given a cyclic chain,
439	// but it matches the Go 1 behavior.
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	// Check for marshaler.
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	// Check for text marshaler.
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	// Slices and arrays iterate over the elements. They do not have an enclosing tag.
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	// Create start element.
488	// Precedence for the XML element name is:
489	// 0. startTemplate
490	// 1. XMLName field in underlying struct;
491	// 2. field name/tag in the struct field; and
492	// 3. type name
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			// Truncate generic instantiation name. See issue 48318.
516			name = name[:i]
517		}
518		if name == "" {
519			return &UnsupportedTypeError{typ}
520		}
521		start.Name.Local = name
522	}
523
524	// Attributes
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	// If an empty name was found, namespace is overridden with an empty space
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// marshalAttr marshals an attribute with the given name and value, adding to start.Attr.
580func (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	// Dereference or skip nil pointer, interface values.
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	// Walk slices.
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// defaultStart returns the default start element to use,
664// given the reflect type, field info, and start template.
665func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement {
666	var start StartElement
667	// Precedence for the XML element name is as above,
668	// except that we do not look inside structs for the first field.
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		// Must be a pointer to a named type,
679		// since it has the Marshaler methods.
680		start.Name.Local = typ.Elem().Name()
681	}
682	return start
683}
684
685// marshalInterface marshals a Marshaler interface value.
686func (p *printer) marshalInterface(val Marshaler, start StartElement) error {
687	// Push a marker onto the tag stack so that MarshalXML
688	// cannot close the XML tags that it did not open.
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	// Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark.
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// marshalTextInterface marshals a TextMarshaler interface value.
706func (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// writeStart writes the given start element.
719func (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	// Attributes
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
757func (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
781func (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		// [...]byte
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		// []byte
811		return "", val.Bytes(), nil
812	}
813	return "", nil, &UnsupportedTypeError{typ}
814}
815
816var ddBytes = []byte("--")
817
818// indirect drills into interfaces and pointers, returning the pointed-at value.
819// If it encounters a nil interface or pointer, indirect returns that nil value.
820// This can turn into an infinite loop given a cyclic chain,
821// but it matches the Go 1 behavior.
822func 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
832func (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			// The field is behind an anonymous struct field that's
842			// nil. Skip it.
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				// "--->" is invalid grammar. Make it "- -->"
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// Write implements io.Writer
988func (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// WriteString implements io.StringWriter
999func (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// WriteByte implements io.ByteWriter
1010func (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// Close the Encoder, indicating that no more data will be written. It flushes
1021// any buffered XML to the underlying writer and returns an error if the
1022// written XML is invalid (e.g. by containing unclosed elements).
1023func (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// return the bufio Writer's cached write error
1038func (p *printer) cachedWriteError() error {
1039	_, err := p.Write(nil)
1040	return err
1041}
1042
1043func (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
1074type parentStack struct {
1075	p     *printer
1076	stack []string
1077}
1078
1079// trim updates the XML context to match the longest common prefix of the stack
1080// and the given parents. A closing tag will be written for every parent
1081// popped. Passing a zero slice or nil will close all the elements.
1082func (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// push adds parent elements to the stack and writes open tags.
1099func (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// UnsupportedTypeError is returned when [Marshal] encounters a type
1110// that cannot be converted into XML.
1111type UnsupportedTypeError struct {
1112	Type reflect.Type
1113}
1114
1115func (e *UnsupportedTypeError) Error() string {
1116	return "xml: unsupported type: " + e.Type.String()
1117}
1118
1119func 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