github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/encoding/xml/marshal.go (about)

     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  
     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  	// 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.
    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  // 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.
   108  type 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.
   123  type 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.
   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  // An Encoder writes XML data to an output stream.
   144  type Encoder struct {
   145  	p printer
   146  }
   147  
   148  // NewEncoder returns a new encoder that writes to w.
   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  // 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.
   158  func (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 Flush before returning.
   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  // 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 Flush before returning.
   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  // 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 Flush, because usually it is part of a larger operation
   202  // such as Encode or 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.
   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  		// 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.
   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  			// 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 EncodeToken documentation for details about when it is necessary.
   307  func (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).
   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 // 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.
   337  func (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.
   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.TypeOf((*Marshaler)(nil)).Elem()
   419  	marshalerAttrType = reflect.TypeOf((*MarshalerAttr)(nil)).Elem()
   420  	textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
   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.
   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  	// 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 a name was found, namespace is overridden with an empty space
   547  	if tinfo.xmlname != nil && start.Name.Space == "" &&
   548  		len(p.tags) != 0 && p.tags[len(p.tags)-1].Space != "" {
   549  		start.Attr = append(start.Attr, Attr{Name{"", xmlnsPrefix}, ""})
   550  	}
   551  	if err := p.writeStart(&start); err != nil {
   552  		return err
   553  	}
   554  
   555  	if val.Kind() == reflect.Struct {
   556  		err = p.marshalStruct(tinfo, val)
   557  	} else {
   558  		s, b, err1 := p.marshalSimple(typ, val)
   559  		if err1 != nil {
   560  			err = err1
   561  		} else if b != nil {
   562  			EscapeText(p, b)
   563  		} else {
   564  			p.EscapeString(s)
   565  		}
   566  	}
   567  	if err != nil {
   568  		return err
   569  	}
   570  
   571  	if err := p.writeEnd(start.Name); err != nil {
   572  		return err
   573  	}
   574  
   575  	return p.cachedWriteError()
   576  }
   577  
   578  // marshalAttr marshals an attribute with the given name and value, adding to start.Attr.
   579  func (p *printer) marshalAttr(start *StartElement, name Name, val reflect.Value) error {
   580  	if val.CanInterface() && val.Type().Implements(marshalerAttrType) {
   581  		attr, err := val.Interface().(MarshalerAttr).MarshalXMLAttr(name)
   582  		if err != nil {
   583  			return err
   584  		}
   585  		if attr.Name.Local != "" {
   586  			start.Attr = append(start.Attr, attr)
   587  		}
   588  		return nil
   589  	}
   590  
   591  	if val.CanAddr() {
   592  		pv := val.Addr()
   593  		if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) {
   594  			attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name)
   595  			if err != nil {
   596  				return err
   597  			}
   598  			if attr.Name.Local != "" {
   599  				start.Attr = append(start.Attr, attr)
   600  			}
   601  			return nil
   602  		}
   603  	}
   604  
   605  	if val.CanInterface() && val.Type().Implements(textMarshalerType) {
   606  		text, err := val.Interface().(encoding.TextMarshaler).MarshalText()
   607  		if err != nil {
   608  			return err
   609  		}
   610  		start.Attr = append(start.Attr, Attr{name, string(text)})
   611  		return nil
   612  	}
   613  
   614  	if val.CanAddr() {
   615  		pv := val.Addr()
   616  		if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
   617  			text, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
   618  			if err != nil {
   619  				return err
   620  			}
   621  			start.Attr = append(start.Attr, Attr{name, string(text)})
   622  			return nil
   623  		}
   624  	}
   625  
   626  	// Dereference or skip nil pointer, interface values.
   627  	switch val.Kind() {
   628  	case reflect.Pointer, reflect.Interface:
   629  		if val.IsNil() {
   630  			return nil
   631  		}
   632  		val = val.Elem()
   633  	}
   634  
   635  	// Walk slices.
   636  	if val.Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
   637  		n := val.Len()
   638  		for i := 0; i < n; i++ {
   639  			if err := p.marshalAttr(start, name, val.Index(i)); err != nil {
   640  				return err
   641  			}
   642  		}
   643  		return nil
   644  	}
   645  
   646  	if val.Type() == attrType {
   647  		start.Attr = append(start.Attr, val.Interface().(Attr))
   648  		return nil
   649  	}
   650  
   651  	s, b, err := p.marshalSimple(val.Type(), val)
   652  	if err != nil {
   653  		return err
   654  	}
   655  	if b != nil {
   656  		s = string(b)
   657  	}
   658  	start.Attr = append(start.Attr, Attr{name, s})
   659  	return nil
   660  }
   661  
   662  // defaultStart returns the default start element to use,
   663  // given the reflect type, field info, and start template.
   664  func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement {
   665  	var start StartElement
   666  	// Precedence for the XML element name is as above,
   667  	// except that we do not look inside structs for the first field.
   668  	if startTemplate != nil {
   669  		start.Name = startTemplate.Name
   670  		start.Attr = append(start.Attr, startTemplate.Attr...)
   671  	} else if finfo != nil && finfo.name != "" {
   672  		start.Name.Local = finfo.name
   673  		start.Name.Space = finfo.xmlns
   674  	} else if typ.Name() != "" {
   675  		start.Name.Local = typ.Name()
   676  	} else {
   677  		// Must be a pointer to a named type,
   678  		// since it has the Marshaler methods.
   679  		start.Name.Local = typ.Elem().Name()
   680  	}
   681  	return start
   682  }
   683  
   684  // marshalInterface marshals a Marshaler interface value.
   685  func (p *printer) marshalInterface(val Marshaler, start StartElement) error {
   686  	// Push a marker onto the tag stack so that MarshalXML
   687  	// cannot close the XML tags that it did not open.
   688  	p.tags = append(p.tags, Name{})
   689  	n := len(p.tags)
   690  
   691  	err := val.MarshalXML(p.encoder, start)
   692  	if err != nil {
   693  		return err
   694  	}
   695  
   696  	// Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark.
   697  	if len(p.tags) > n {
   698  		return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local)
   699  	}
   700  	p.tags = p.tags[:n-1]
   701  	return nil
   702  }
   703  
   704  // marshalTextInterface marshals a TextMarshaler interface value.
   705  func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error {
   706  	if err := p.writeStart(&start); err != nil {
   707  		return err
   708  	}
   709  	text, err := val.MarshalText()
   710  	if err != nil {
   711  		return err
   712  	}
   713  	EscapeText(p, text)
   714  	return p.writeEnd(start.Name)
   715  }
   716  
   717  // writeStart writes the given start element.
   718  func (p *printer) writeStart(start *StartElement) error {
   719  	if start.Name.Local == "" {
   720  		return fmt.Errorf("xml: start tag with no name")
   721  	}
   722  
   723  	p.tags = append(p.tags, start.Name)
   724  	p.markPrefix()
   725  
   726  	p.writeIndent(1)
   727  	p.WriteByte('<')
   728  	p.WriteString(start.Name.Local)
   729  
   730  	if start.Name.Space != "" {
   731  		p.WriteString(` xmlns="`)
   732  		p.EscapeString(start.Name.Space)
   733  		p.WriteByte('"')
   734  	}
   735  
   736  	// Attributes
   737  	for _, attr := range start.Attr {
   738  		name := attr.Name
   739  		if name.Local == "" {
   740  			continue
   741  		}
   742  		p.WriteByte(' ')
   743  		if name.Space != "" {
   744  			p.WriteString(p.createAttrPrefix(name.Space))
   745  			p.WriteByte(':')
   746  		}
   747  		p.WriteString(name.Local)
   748  		p.WriteString(`="`)
   749  		p.EscapeString(attr.Value)
   750  		p.WriteByte('"')
   751  	}
   752  	p.WriteByte('>')
   753  	return nil
   754  }
   755  
   756  func (p *printer) writeEnd(name Name) error {
   757  	if name.Local == "" {
   758  		return fmt.Errorf("xml: end tag with no name")
   759  	}
   760  	if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" {
   761  		return fmt.Errorf("xml: end tag </%s> without start tag", name.Local)
   762  	}
   763  	if top := p.tags[len(p.tags)-1]; top != name {
   764  		if top.Local != name.Local {
   765  			return fmt.Errorf("xml: end tag </%s> does not match start tag <%s>", name.Local, top.Local)
   766  		}
   767  		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)
   768  	}
   769  	p.tags = p.tags[:len(p.tags)-1]
   770  
   771  	p.writeIndent(-1)
   772  	p.WriteByte('<')
   773  	p.WriteByte('/')
   774  	p.WriteString(name.Local)
   775  	p.WriteByte('>')
   776  	p.popPrefix()
   777  	return nil
   778  }
   779  
   780  func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) {
   781  	switch val.Kind() {
   782  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   783  		return strconv.FormatInt(val.Int(), 10), nil, nil
   784  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   785  		return strconv.FormatUint(val.Uint(), 10), nil, nil
   786  	case reflect.Float32, reflect.Float64:
   787  		return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil
   788  	case reflect.String:
   789  		return val.String(), nil, nil
   790  	case reflect.Bool:
   791  		return strconv.FormatBool(val.Bool()), nil, nil
   792  	case reflect.Array:
   793  		if typ.Elem().Kind() != reflect.Uint8 {
   794  			break
   795  		}
   796  		// [...]byte
   797  		var bytes []byte
   798  		if val.CanAddr() {
   799  			bytes = val.Slice(0, val.Len()).Bytes()
   800  		} else {
   801  			bytes = make([]byte, val.Len())
   802  			reflect.Copy(reflect.ValueOf(bytes), val)
   803  		}
   804  		return "", bytes, nil
   805  	case reflect.Slice:
   806  		if typ.Elem().Kind() != reflect.Uint8 {
   807  			break
   808  		}
   809  		// []byte
   810  		return "", val.Bytes(), nil
   811  	}
   812  	return "", nil, &UnsupportedTypeError{typ}
   813  }
   814  
   815  var ddBytes = []byte("--")
   816  
   817  // indirect drills into interfaces and pointers, returning the pointed-at value.
   818  // If it encounters a nil interface or pointer, indirect returns that nil value.
   819  // This can turn into an infinite loop given a cyclic chain,
   820  // but it matches the Go 1 behavior.
   821  func indirect(vf reflect.Value) reflect.Value {
   822  	for vf.Kind() == reflect.Interface || vf.Kind() == reflect.Pointer {
   823  		if vf.IsNil() {
   824  			return vf
   825  		}
   826  		vf = vf.Elem()
   827  	}
   828  	return vf
   829  }
   830  
   831  func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error {
   832  	s := parentStack{p: p}
   833  	for i := range tinfo.fields {
   834  		finfo := &tinfo.fields[i]
   835  		if finfo.flags&fAttr != 0 {
   836  			continue
   837  		}
   838  		vf := finfo.value(val, dontInitNilPointers)
   839  		if !vf.IsValid() {
   840  			// The field is behind an anonymous struct field that's
   841  			// nil. Skip it.
   842  			continue
   843  		}
   844  
   845  		switch finfo.flags & fMode {
   846  		case fCDATA, fCharData:
   847  			emit := EscapeText
   848  			if finfo.flags&fMode == fCDATA {
   849  				emit = emitCDATA
   850  			}
   851  			if err := s.trim(finfo.parents); err != nil {
   852  				return err
   853  			}
   854  			if vf.CanInterface() && vf.Type().Implements(textMarshalerType) {
   855  				data, err := vf.Interface().(encoding.TextMarshaler).MarshalText()
   856  				if err != nil {
   857  					return err
   858  				}
   859  				if err := emit(p, data); err != nil {
   860  					return err
   861  				}
   862  				continue
   863  			}
   864  			if vf.CanAddr() {
   865  				pv := vf.Addr()
   866  				if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
   867  					data, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
   868  					if err != nil {
   869  						return err
   870  					}
   871  					if err := emit(p, data); err != nil {
   872  						return err
   873  					}
   874  					continue
   875  				}
   876  			}
   877  
   878  			var scratch [64]byte
   879  			vf = indirect(vf)
   880  			switch vf.Kind() {
   881  			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   882  				if err := emit(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)); err != nil {
   883  					return err
   884  				}
   885  			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   886  				if err := emit(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)); err != nil {
   887  					return err
   888  				}
   889  			case reflect.Float32, reflect.Float64:
   890  				if err := emit(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())); err != nil {
   891  					return err
   892  				}
   893  			case reflect.Bool:
   894  				if err := emit(p, strconv.AppendBool(scratch[:0], vf.Bool())); err != nil {
   895  					return err
   896  				}
   897  			case reflect.String:
   898  				if err := emit(p, []byte(vf.String())); err != nil {
   899  					return err
   900  				}
   901  			case reflect.Slice:
   902  				if elem, ok := vf.Interface().([]byte); ok {
   903  					if err := emit(p, elem); err != nil {
   904  						return err
   905  					}
   906  				}
   907  			}
   908  			continue
   909  
   910  		case fComment:
   911  			if err := s.trim(finfo.parents); err != nil {
   912  				return err
   913  			}
   914  			vf = indirect(vf)
   915  			k := vf.Kind()
   916  			if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) {
   917  				return fmt.Errorf("xml: bad type for comment field of %s", val.Type())
   918  			}
   919  			if vf.Len() == 0 {
   920  				continue
   921  			}
   922  			p.writeIndent(0)
   923  			p.WriteString("<!--")
   924  			dashDash := false
   925  			dashLast := false
   926  			switch k {
   927  			case reflect.String:
   928  				s := vf.String()
   929  				dashDash = strings.Contains(s, "--")
   930  				dashLast = s[len(s)-1] == '-'
   931  				if !dashDash {
   932  					p.WriteString(s)
   933  				}
   934  			case reflect.Slice:
   935  				b := vf.Bytes()
   936  				dashDash = bytes.Contains(b, ddBytes)
   937  				dashLast = b[len(b)-1] == '-'
   938  				if !dashDash {
   939  					p.Write(b)
   940  				}
   941  			default:
   942  				panic("can't happen")
   943  			}
   944  			if dashDash {
   945  				return fmt.Errorf(`xml: comments must not contain "--"`)
   946  			}
   947  			if dashLast {
   948  				// "--->" is invalid grammar. Make it "- -->"
   949  				p.WriteByte(' ')
   950  			}
   951  			p.WriteString("-->")
   952  			continue
   953  
   954  		case fInnerXML:
   955  			vf = indirect(vf)
   956  			iface := vf.Interface()
   957  			switch raw := iface.(type) {
   958  			case []byte:
   959  				p.Write(raw)
   960  				continue
   961  			case string:
   962  				p.WriteString(raw)
   963  				continue
   964  			}
   965  
   966  		case fElement, fElement | fAny:
   967  			if err := s.trim(finfo.parents); err != nil {
   968  				return err
   969  			}
   970  			if len(finfo.parents) > len(s.stack) {
   971  				if vf.Kind() != reflect.Pointer && vf.Kind() != reflect.Interface || !vf.IsNil() {
   972  					if err := s.push(finfo.parents[len(s.stack):]); err != nil {
   973  						return err
   974  					}
   975  				}
   976  			}
   977  		}
   978  		if err := p.marshalValue(vf, finfo, nil); err != nil {
   979  			return err
   980  		}
   981  	}
   982  	s.trim(nil)
   983  	return p.cachedWriteError()
   984  }
   985  
   986  // Write implements io.Writer
   987  func (p *printer) Write(b []byte) (n int, err error) {
   988  	if p.closed && p.err == nil {
   989  		p.err = errors.New("use of closed Encoder")
   990  	}
   991  	if p.err == nil {
   992  		n, p.err = p.w.Write(b)
   993  	}
   994  	return n, p.err
   995  }
   996  
   997  // WriteString implements io.StringWriter
   998  func (p *printer) WriteString(s string) (n int, err error) {
   999  	if p.closed && p.err == nil {
  1000  		p.err = errors.New("use of closed Encoder")
  1001  	}
  1002  	if p.err == nil {
  1003  		n, p.err = p.w.WriteString(s)
  1004  	}
  1005  	return n, p.err
  1006  }
  1007  
  1008  // WriteByte implements io.ByteWriter
  1009  func (p *printer) WriteByte(c byte) error {
  1010  	if p.closed && p.err == nil {
  1011  		p.err = errors.New("use of closed Encoder")
  1012  	}
  1013  	if p.err == nil {
  1014  		p.err = p.w.WriteByte(c)
  1015  	}
  1016  	return p.err
  1017  }
  1018  
  1019  // Close the Encoder, indicating that no more data will be written. It flushes
  1020  // any buffered XML to the underlying writer and returns an error if the
  1021  // written XML is invalid (e.g. by containing unclosed elements).
  1022  func (p *printer) Close() error {
  1023  	if p.closed {
  1024  		return nil
  1025  	}
  1026  	p.closed = true
  1027  	if err := p.w.Flush(); err != nil {
  1028  		return err
  1029  	}
  1030  	if len(p.tags) > 0 {
  1031  		return fmt.Errorf("unclosed tag <%s>", p.tags[len(p.tags)-1].Local)
  1032  	}
  1033  	return nil
  1034  }
  1035  
  1036  // return the bufio Writer's cached write error
  1037  func (p *printer) cachedWriteError() error {
  1038  	_, err := p.Write(nil)
  1039  	return err
  1040  }
  1041  
  1042  func (p *printer) writeIndent(depthDelta int) {
  1043  	if len(p.prefix) == 0 && len(p.indent) == 0 {
  1044  		return
  1045  	}
  1046  	if depthDelta < 0 {
  1047  		p.depth--
  1048  		if p.indentedIn {
  1049  			p.indentedIn = false
  1050  			return
  1051  		}
  1052  		p.indentedIn = false
  1053  	}
  1054  	if p.putNewline {
  1055  		p.WriteByte('\n')
  1056  	} else {
  1057  		p.putNewline = true
  1058  	}
  1059  	if len(p.prefix) > 0 {
  1060  		p.WriteString(p.prefix)
  1061  	}
  1062  	if len(p.indent) > 0 {
  1063  		for i := 0; i < p.depth; i++ {
  1064  			p.WriteString(p.indent)
  1065  		}
  1066  	}
  1067  	if depthDelta > 0 {
  1068  		p.depth++
  1069  		p.indentedIn = true
  1070  	}
  1071  }
  1072  
  1073  type parentStack struct {
  1074  	p     *printer
  1075  	stack []string
  1076  }
  1077  
  1078  // trim updates the XML context to match the longest common prefix of the stack
  1079  // and the given parents. A closing tag will be written for every parent
  1080  // popped. Passing a zero slice or nil will close all the elements.
  1081  func (s *parentStack) trim(parents []string) error {
  1082  	split := 0
  1083  	for ; split < len(parents) && split < len(s.stack); split++ {
  1084  		if parents[split] != s.stack[split] {
  1085  			break
  1086  		}
  1087  	}
  1088  	for i := len(s.stack) - 1; i >= split; i-- {
  1089  		if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil {
  1090  			return err
  1091  		}
  1092  	}
  1093  	s.stack = s.stack[:split]
  1094  	return nil
  1095  }
  1096  
  1097  // push adds parent elements to the stack and writes open tags.
  1098  func (s *parentStack) push(parents []string) error {
  1099  	for i := 0; i < len(parents); i++ {
  1100  		if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil {
  1101  			return err
  1102  		}
  1103  	}
  1104  	s.stack = append(s.stack, parents...)
  1105  	return nil
  1106  }
  1107  
  1108  // UnsupportedTypeError is returned when Marshal encounters a type
  1109  // that cannot be converted into XML.
  1110  type UnsupportedTypeError struct {
  1111  	Type reflect.Type
  1112  }
  1113  
  1114  func (e *UnsupportedTypeError) Error() string {
  1115  	return "xml: unsupported type: " + e.Type.String()
  1116  }
  1117  
  1118  func isEmptyValue(v reflect.Value) bool {
  1119  	switch v.Kind() {
  1120  	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  1121  		return v.Len() == 0
  1122  	case reflect.Bool:
  1123  		return !v.Bool()
  1124  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1125  		return v.Int() == 0
  1126  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1127  		return v.Uint() == 0
  1128  	case reflect.Float32, reflect.Float64:
  1129  		return v.Float() == 0
  1130  	case reflect.Interface, reflect.Pointer:
  1131  		return v.IsNil()
  1132  	}
  1133  	return false
  1134  }