Source file src/encoding/xml/marshal.go

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

View as plain text