github.com/sean-/go@v0.0.0-20151219100004-97f854cd7bb6/src/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  	"fmt"
    12  	"io"
    13  	"reflect"
    14  	"strconv"
    15  	"strings"
    16  )
    17  
    18  const (
    19  	// A generic XML header suitable for use with the output of Marshal.
    20  	// This is not automatically added to any output of this package,
    21  	// it is provided as a convenience.
    22  	Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
    23  )
    24  
    25  // Marshal returns the XML encoding of v.
    26  //
    27  // Marshal handles an array or slice by marshalling each of the elements.
    28  // Marshal handles a pointer by marshalling the value it points at or, if the
    29  // pointer is nil, by writing nothing.  Marshal handles an interface value by
    30  // marshalling the value it contains or, if the interface value is nil, by
    31  // writing nothing.  Marshal handles all other data by writing one or more XML
    32  // elements containing the data.
    33  //
    34  // The name for the XML elements is taken from, in order of preference:
    35  //     - the tag on the XMLName field, if the data is a struct
    36  //     - the value of the XMLName field of type xml.Name
    37  //     - the tag of the struct field used to obtain the data
    38  //     - the name of the struct field used to obtain the data
    39  //     - the name of the marshalled type
    40  //
    41  // The XML element for a struct contains marshalled elements for each of the
    42  // exported fields of the struct, with these exceptions:
    43  //     - the XMLName field, described above, is omitted.
    44  //     - a field with tag "-" is omitted.
    45  //     - a field with tag "name,attr" becomes an attribute with
    46  //       the given name in the XML element.
    47  //     - a field with tag ",attr" becomes an attribute with the
    48  //       field name in the XML element.
    49  //     - a field with tag ",chardata" is written as character data,
    50  //       not as an XML element.
    51  //     - a field with tag ",cdata" is written as character data
    52  //       wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element.
    53  //     - a field with tag ",innerxml" is written verbatim, not subject
    54  //       to the usual marshalling procedure.
    55  //     - a field with tag ",comment" is written as an XML comment, not
    56  //       subject to the usual marshalling procedure. It must not contain
    57  //       the "--" string within it.
    58  //     - a field with a tag including the "omitempty" option is omitted
    59  //       if the field value is empty. The empty values are false, 0, any
    60  //       nil pointer or interface value, and any array, slice, map, or
    61  //       string of length zero.
    62  //     - an anonymous struct field is handled as if the fields of its
    63  //       value were part of the outer struct.
    64  //
    65  // If a field uses a tag "a>b>c", then the element c will be nested inside
    66  // parent elements a and b.  Fields that appear next to each other that name
    67  // the same parent will be enclosed in one XML element.
    68  //
    69  // See MarshalIndent for an example.
    70  //
    71  // Marshal will return an error if asked to marshal a channel, function, or map.
    72  func Marshal(v interface{}) ([]byte, error) {
    73  	var b bytes.Buffer
    74  	if err := NewEncoder(&b).Encode(v); err != nil {
    75  		return nil, err
    76  	}
    77  	return b.Bytes(), nil
    78  }
    79  
    80  // Marshaler is the interface implemented by objects that can marshal
    81  // themselves into valid XML elements.
    82  //
    83  // MarshalXML encodes the receiver as zero or more XML elements.
    84  // By convention, arrays or slices are typically encoded as a sequence
    85  // of elements, one per entry.
    86  // Using start as the element tag is not required, but doing so
    87  // will enable Unmarshal to match the XML elements to the correct
    88  // struct field.
    89  // One common implementation strategy is to construct a separate
    90  // value with a layout corresponding to the desired XML and then
    91  // to encode it using e.EncodeElement.
    92  // Another common strategy is to use repeated calls to e.EncodeToken
    93  // to generate the XML output one token at a time.
    94  // The sequence of encoded tokens must make up zero or more valid
    95  // XML elements.
    96  type Marshaler interface {
    97  	MarshalXML(e *Encoder, start StartElement) error
    98  }
    99  
   100  // MarshalerAttr is the interface implemented by objects that can marshal
   101  // themselves into valid XML attributes.
   102  //
   103  // MarshalXMLAttr returns an XML attribute with the encoded value of the receiver.
   104  // Using name as the attribute name is not required, but doing so
   105  // will enable Unmarshal to match the attribute to the correct
   106  // struct field.
   107  // If MarshalXMLAttr returns the zero attribute Attr{}, no attribute
   108  // will be generated in the output.
   109  // MarshalXMLAttr is used only for struct fields with the
   110  // "attr" option in the field tag.
   111  type MarshalerAttr interface {
   112  	MarshalXMLAttr(name Name) (Attr, error)
   113  }
   114  
   115  // MarshalIndent works like Marshal, but each XML element begins on a new
   116  // indented line that starts with prefix and is followed by one or more
   117  // copies of indent according to the nesting depth.
   118  func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
   119  	var b bytes.Buffer
   120  	enc := NewEncoder(&b)
   121  	enc.Indent(prefix, indent)
   122  	if err := enc.Encode(v); err != nil {
   123  		return nil, err
   124  	}
   125  	return b.Bytes(), nil
   126  }
   127  
   128  // An Encoder writes XML data to an output stream.
   129  type Encoder struct {
   130  	p printer
   131  }
   132  
   133  // NewEncoder returns a new encoder that writes to w.
   134  func NewEncoder(w io.Writer) *Encoder {
   135  	e := &Encoder{printer{Writer: bufio.NewWriter(w)}}
   136  	e.p.encoder = e
   137  	return e
   138  }
   139  
   140  // Indent sets the encoder to generate XML in which each element
   141  // begins on a new indented line that starts with prefix and is followed by
   142  // one or more copies of indent according to the nesting depth.
   143  func (enc *Encoder) Indent(prefix, indent string) {
   144  	enc.p.prefix = prefix
   145  	enc.p.indent = indent
   146  }
   147  
   148  // Encode writes the XML encoding of v to the stream.
   149  //
   150  // See the documentation for Marshal for details about the conversion
   151  // of Go values to XML.
   152  //
   153  // Encode calls Flush before returning.
   154  func (enc *Encoder) Encode(v interface{}) error {
   155  	err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil)
   156  	if err != nil {
   157  		return err
   158  	}
   159  	return enc.p.Flush()
   160  }
   161  
   162  // EncodeElement writes the XML encoding of v to the stream,
   163  // using start as the outermost tag in the encoding.
   164  //
   165  // See the documentation for Marshal for details about the conversion
   166  // of Go values to XML.
   167  //
   168  // EncodeElement calls Flush before returning.
   169  func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error {
   170  	err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start)
   171  	if err != nil {
   172  		return err
   173  	}
   174  	return enc.p.Flush()
   175  }
   176  
   177  var (
   178  	begComment   = []byte("<!--")
   179  	endComment   = []byte("-->")
   180  	endProcInst  = []byte("?>")
   181  	endDirective = []byte(">")
   182  )
   183  
   184  // EncodeToken writes the given XML token to the stream.
   185  // It returns an error if StartElement and EndElement tokens are not properly matched.
   186  //
   187  // EncodeToken does not call Flush, because usually it is part of a larger operation
   188  // such as Encode or EncodeElement (or a custom Marshaler's MarshalXML invoked
   189  // during those), and those will call Flush when finished.
   190  // Callers that create an Encoder and then invoke EncodeToken directly, without
   191  // using Encode or EncodeElement, need to call Flush when finished to ensure
   192  // that the XML is written to the underlying writer.
   193  //
   194  // EncodeToken allows writing a ProcInst with Target set to "xml" only as the first token
   195  // in the stream.
   196  func (enc *Encoder) EncodeToken(t Token) error {
   197  
   198  	p := &enc.p
   199  	switch t := t.(type) {
   200  	case StartElement:
   201  		if err := p.writeStart(&t); err != nil {
   202  			return err
   203  		}
   204  	case EndElement:
   205  		if err := p.writeEnd(t.Name); err != nil {
   206  			return err
   207  		}
   208  	case CharData:
   209  		escapeText(p, t, false)
   210  	case Comment:
   211  		if bytes.Contains(t, endComment) {
   212  			return fmt.Errorf("xml: EncodeToken of Comment containing --> marker")
   213  		}
   214  		p.WriteString("<!--")
   215  		p.Write(t)
   216  		p.WriteString("-->")
   217  		return p.cachedWriteError()
   218  	case ProcInst:
   219  		// First token to be encoded which is also a ProcInst with target of xml
   220  		// is the xml declaration.  The only ProcInst where target of xml is allowed.
   221  		if t.Target == "xml" && p.Buffered() != 0 {
   222  			return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded")
   223  		}
   224  		if !isNameString(t.Target) {
   225  			return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target")
   226  		}
   227  		if bytes.Contains(t.Inst, endProcInst) {
   228  			return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker")
   229  		}
   230  		p.WriteString("<?")
   231  		p.WriteString(t.Target)
   232  		if len(t.Inst) > 0 {
   233  			p.WriteByte(' ')
   234  			p.Write(t.Inst)
   235  		}
   236  		p.WriteString("?>")
   237  	case Directive:
   238  		if !isValidDirective(t) {
   239  			return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers")
   240  		}
   241  		p.WriteString("<!")
   242  		p.Write(t)
   243  		p.WriteString(">")
   244  	default:
   245  		return fmt.Errorf("xml: EncodeToken of invalid token type")
   246  
   247  	}
   248  	return p.cachedWriteError()
   249  }
   250  
   251  // isValidDirective reports whether dir is a valid directive text,
   252  // meaning angle brackets are matched, ignoring comments and strings.
   253  func isValidDirective(dir Directive) bool {
   254  	var (
   255  		depth     int
   256  		inquote   uint8
   257  		incomment bool
   258  	)
   259  	for i, c := range dir {
   260  		switch {
   261  		case incomment:
   262  			if c == '>' {
   263  				if n := 1 + i - len(endComment); n >= 0 && bytes.Equal(dir[n:i+1], endComment) {
   264  					incomment = false
   265  				}
   266  			}
   267  			// Just ignore anything in comment
   268  		case inquote != 0:
   269  			if c == inquote {
   270  				inquote = 0
   271  			}
   272  			// Just ignore anything within quotes
   273  		case c == '\'' || c == '"':
   274  			inquote = c
   275  		case c == '<':
   276  			if i+len(begComment) < len(dir) && bytes.Equal(dir[i:i+len(begComment)], begComment) {
   277  				incomment = true
   278  			} else {
   279  				depth++
   280  			}
   281  		case c == '>':
   282  			if depth == 0 {
   283  				return false
   284  			}
   285  			depth--
   286  		}
   287  	}
   288  	return depth == 0 && inquote == 0 && !incomment
   289  }
   290  
   291  // Flush flushes any buffered XML to the underlying writer.
   292  // See the EncodeToken documentation for details about when it is necessary.
   293  func (enc *Encoder) Flush() error {
   294  	return enc.p.Flush()
   295  }
   296  
   297  type printer struct {
   298  	*bufio.Writer
   299  	encoder    *Encoder
   300  	seq        int
   301  	indent     string
   302  	prefix     string
   303  	depth      int
   304  	indentedIn bool
   305  	putNewline bool
   306  	attrNS     map[string]string // map prefix -> name space
   307  	attrPrefix map[string]string // map name space -> prefix
   308  	prefixes   []string
   309  	tags       []Name
   310  }
   311  
   312  // createAttrPrefix finds the name space prefix attribute to use for the given name space,
   313  // defining a new prefix if necessary. It returns the prefix.
   314  func (p *printer) createAttrPrefix(url string) string {
   315  	if prefix := p.attrPrefix[url]; prefix != "" {
   316  		return prefix
   317  	}
   318  
   319  	// The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml"
   320  	// and must be referred to that way.
   321  	// (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns",
   322  	// but users should not be trying to use that one directly - that's our job.)
   323  	if url == xmlURL {
   324  		return "xml"
   325  	}
   326  
   327  	// Need to define a new name space.
   328  	if p.attrPrefix == nil {
   329  		p.attrPrefix = make(map[string]string)
   330  		p.attrNS = make(map[string]string)
   331  	}
   332  
   333  	// Pick a name. We try to use the final element of the path
   334  	// but fall back to _.
   335  	prefix := strings.TrimRight(url, "/")
   336  	if i := strings.LastIndex(prefix, "/"); i >= 0 {
   337  		prefix = prefix[i+1:]
   338  	}
   339  	if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") {
   340  		prefix = "_"
   341  	}
   342  	if strings.HasPrefix(prefix, "xml") {
   343  		// xmlanything is reserved.
   344  		prefix = "_" + prefix
   345  	}
   346  	if p.attrNS[prefix] != "" {
   347  		// Name is taken. Find a better one.
   348  		for p.seq++; ; p.seq++ {
   349  			if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" {
   350  				prefix = id
   351  				break
   352  			}
   353  		}
   354  	}
   355  
   356  	p.attrPrefix[url] = prefix
   357  	p.attrNS[prefix] = url
   358  
   359  	p.WriteString(`xmlns:`)
   360  	p.WriteString(prefix)
   361  	p.WriteString(`="`)
   362  	EscapeText(p, []byte(url))
   363  	p.WriteString(`" `)
   364  
   365  	p.prefixes = append(p.prefixes, prefix)
   366  
   367  	return prefix
   368  }
   369  
   370  // deleteAttrPrefix removes an attribute name space prefix.
   371  func (p *printer) deleteAttrPrefix(prefix string) {
   372  	delete(p.attrPrefix, p.attrNS[prefix])
   373  	delete(p.attrNS, prefix)
   374  }
   375  
   376  func (p *printer) markPrefix() {
   377  	p.prefixes = append(p.prefixes, "")
   378  }
   379  
   380  func (p *printer) popPrefix() {
   381  	for len(p.prefixes) > 0 {
   382  		prefix := p.prefixes[len(p.prefixes)-1]
   383  		p.prefixes = p.prefixes[:len(p.prefixes)-1]
   384  		if prefix == "" {
   385  			break
   386  		}
   387  		p.deleteAttrPrefix(prefix)
   388  	}
   389  }
   390  
   391  var (
   392  	marshalerType     = reflect.TypeOf((*Marshaler)(nil)).Elem()
   393  	marshalerAttrType = reflect.TypeOf((*MarshalerAttr)(nil)).Elem()
   394  	textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
   395  )
   396  
   397  // marshalValue writes one or more XML elements representing val.
   398  // If val was obtained from a struct field, finfo must have its details.
   399  func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error {
   400  	if startTemplate != nil && startTemplate.Name.Local == "" {
   401  		return fmt.Errorf("xml: EncodeElement of StartElement with missing name")
   402  	}
   403  
   404  	if !val.IsValid() {
   405  		return nil
   406  	}
   407  	if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) {
   408  		return nil
   409  	}
   410  
   411  	// Drill into interfaces and pointers.
   412  	// This can turn into an infinite loop given a cyclic chain,
   413  	// but it matches the Go 1 behavior.
   414  	for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr {
   415  		if val.IsNil() {
   416  			return nil
   417  		}
   418  		val = val.Elem()
   419  	}
   420  
   421  	kind := val.Kind()
   422  	typ := val.Type()
   423  
   424  	// Check for marshaler.
   425  	if val.CanInterface() && typ.Implements(marshalerType) {
   426  		return p.marshalInterface(val.Interface().(Marshaler), defaultStart(typ, finfo, startTemplate))
   427  	}
   428  	if val.CanAddr() {
   429  		pv := val.Addr()
   430  		if pv.CanInterface() && pv.Type().Implements(marshalerType) {
   431  			return p.marshalInterface(pv.Interface().(Marshaler), defaultStart(pv.Type(), finfo, startTemplate))
   432  		}
   433  	}
   434  
   435  	// Check for text marshaler.
   436  	if val.CanInterface() && typ.Implements(textMarshalerType) {
   437  		return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), defaultStart(typ, finfo, startTemplate))
   438  	}
   439  	if val.CanAddr() {
   440  		pv := val.Addr()
   441  		if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
   442  			return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), defaultStart(pv.Type(), finfo, startTemplate))
   443  		}
   444  	}
   445  
   446  	// Slices and arrays iterate over the elements. They do not have an enclosing tag.
   447  	if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 {
   448  		for i, n := 0, val.Len(); i < n; i++ {
   449  			if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil {
   450  				return err
   451  			}
   452  		}
   453  		return nil
   454  	}
   455  
   456  	tinfo, err := getTypeInfo(typ)
   457  	if err != nil {
   458  		return err
   459  	}
   460  
   461  	// Create start element.
   462  	// Precedence for the XML element name is:
   463  	// 0. startTemplate
   464  	// 1. XMLName field in underlying struct;
   465  	// 2. field name/tag in the struct field; and
   466  	// 3. type name
   467  	var start StartElement
   468  
   469  	if startTemplate != nil {
   470  		start.Name = startTemplate.Name
   471  		start.Attr = append(start.Attr, startTemplate.Attr...)
   472  	} else if tinfo.xmlname != nil {
   473  		xmlname := tinfo.xmlname
   474  		if xmlname.name != "" {
   475  			start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name
   476  		} else if v, ok := xmlname.value(val).Interface().(Name); ok && v.Local != "" {
   477  			start.Name = v
   478  		}
   479  	}
   480  	if start.Name.Local == "" && finfo != nil {
   481  		start.Name.Space, start.Name.Local = finfo.xmlns, finfo.name
   482  	}
   483  	if start.Name.Local == "" {
   484  		name := typ.Name()
   485  		if name == "" {
   486  			return &UnsupportedTypeError{typ}
   487  		}
   488  		start.Name.Local = name
   489  	}
   490  
   491  	// Attributes
   492  	for i := range tinfo.fields {
   493  		finfo := &tinfo.fields[i]
   494  		if finfo.flags&fAttr == 0 {
   495  			continue
   496  		}
   497  		fv := finfo.value(val)
   498  		name := Name{Space: finfo.xmlns, Local: finfo.name}
   499  
   500  		if finfo.flags&fOmitEmpty != 0 && isEmptyValue(fv) {
   501  			continue
   502  		}
   503  
   504  		if fv.Kind() == reflect.Interface && fv.IsNil() {
   505  			continue
   506  		}
   507  
   508  		if fv.CanInterface() && fv.Type().Implements(marshalerAttrType) {
   509  			attr, err := fv.Interface().(MarshalerAttr).MarshalXMLAttr(name)
   510  			if err != nil {
   511  				return err
   512  			}
   513  			if attr.Name.Local != "" {
   514  				start.Attr = append(start.Attr, attr)
   515  			}
   516  			continue
   517  		}
   518  
   519  		if fv.CanAddr() {
   520  			pv := fv.Addr()
   521  			if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) {
   522  				attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name)
   523  				if err != nil {
   524  					return err
   525  				}
   526  				if attr.Name.Local != "" {
   527  					start.Attr = append(start.Attr, attr)
   528  				}
   529  				continue
   530  			}
   531  		}
   532  
   533  		if fv.CanInterface() && fv.Type().Implements(textMarshalerType) {
   534  			text, err := fv.Interface().(encoding.TextMarshaler).MarshalText()
   535  			if err != nil {
   536  				return err
   537  			}
   538  			start.Attr = append(start.Attr, Attr{name, string(text)})
   539  			continue
   540  		}
   541  
   542  		if fv.CanAddr() {
   543  			pv := fv.Addr()
   544  			if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
   545  				text, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
   546  				if err != nil {
   547  					return err
   548  				}
   549  				start.Attr = append(start.Attr, Attr{name, string(text)})
   550  				continue
   551  			}
   552  		}
   553  
   554  		// Dereference or skip nil pointer, interface values.
   555  		switch fv.Kind() {
   556  		case reflect.Ptr, reflect.Interface:
   557  			if fv.IsNil() {
   558  				continue
   559  			}
   560  			fv = fv.Elem()
   561  		}
   562  
   563  		s, b, err := p.marshalSimple(fv.Type(), fv)
   564  		if err != nil {
   565  			return err
   566  		}
   567  		if b != nil {
   568  			s = string(b)
   569  		}
   570  		start.Attr = append(start.Attr, Attr{name, s})
   571  	}
   572  
   573  	if err := p.writeStart(&start); err != nil {
   574  		return err
   575  	}
   576  
   577  	if val.Kind() == reflect.Struct {
   578  		err = p.marshalStruct(tinfo, val)
   579  	} else {
   580  		s, b, err1 := p.marshalSimple(typ, val)
   581  		if err1 != nil {
   582  			err = err1
   583  		} else if b != nil {
   584  			EscapeText(p, b)
   585  		} else {
   586  			p.EscapeString(s)
   587  		}
   588  	}
   589  	if err != nil {
   590  		return err
   591  	}
   592  
   593  	if err := p.writeEnd(start.Name); err != nil {
   594  		return err
   595  	}
   596  
   597  	return p.cachedWriteError()
   598  }
   599  
   600  // defaultStart returns the default start element to use,
   601  // given the reflect type, field info, and start template.
   602  func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement {
   603  	var start StartElement
   604  	// Precedence for the XML element name is as above,
   605  	// except that we do not look inside structs for the first field.
   606  	if startTemplate != nil {
   607  		start.Name = startTemplate.Name
   608  		start.Attr = append(start.Attr, startTemplate.Attr...)
   609  	} else if finfo != nil && finfo.name != "" {
   610  		start.Name.Local = finfo.name
   611  		start.Name.Space = finfo.xmlns
   612  	} else if typ.Name() != "" {
   613  		start.Name.Local = typ.Name()
   614  	} else {
   615  		// Must be a pointer to a named type,
   616  		// since it has the Marshaler methods.
   617  		start.Name.Local = typ.Elem().Name()
   618  	}
   619  	return start
   620  }
   621  
   622  // marshalInterface marshals a Marshaler interface value.
   623  func (p *printer) marshalInterface(val Marshaler, start StartElement) error {
   624  	// Push a marker onto the tag stack so that MarshalXML
   625  	// cannot close the XML tags that it did not open.
   626  	p.tags = append(p.tags, Name{})
   627  	n := len(p.tags)
   628  
   629  	err := val.MarshalXML(p.encoder, start)
   630  	if err != nil {
   631  		return err
   632  	}
   633  
   634  	// Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark.
   635  	if len(p.tags) > n {
   636  		return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local)
   637  	}
   638  	p.tags = p.tags[:n-1]
   639  	return nil
   640  }
   641  
   642  // marshalTextInterface marshals a TextMarshaler interface value.
   643  func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error {
   644  	if err := p.writeStart(&start); err != nil {
   645  		return err
   646  	}
   647  	text, err := val.MarshalText()
   648  	if err != nil {
   649  		return err
   650  	}
   651  	EscapeText(p, text)
   652  	return p.writeEnd(start.Name)
   653  }
   654  
   655  // writeStart writes the given start element.
   656  func (p *printer) writeStart(start *StartElement) error {
   657  	if start.Name.Local == "" {
   658  		return fmt.Errorf("xml: start tag with no name")
   659  	}
   660  
   661  	p.tags = append(p.tags, start.Name)
   662  	p.markPrefix()
   663  
   664  	p.writeIndent(1)
   665  	p.WriteByte('<')
   666  	p.WriteString(start.Name.Local)
   667  
   668  	if start.Name.Space != "" {
   669  		p.WriteString(` xmlns="`)
   670  		p.EscapeString(start.Name.Space)
   671  		p.WriteByte('"')
   672  	}
   673  
   674  	// Attributes
   675  	for _, attr := range start.Attr {
   676  		name := attr.Name
   677  		if name.Local == "" {
   678  			continue
   679  		}
   680  		p.WriteByte(' ')
   681  		if name.Space != "" {
   682  			p.WriteString(p.createAttrPrefix(name.Space))
   683  			p.WriteByte(':')
   684  		}
   685  		p.WriteString(name.Local)
   686  		p.WriteString(`="`)
   687  		p.EscapeString(attr.Value)
   688  		p.WriteByte('"')
   689  	}
   690  	p.WriteByte('>')
   691  	return nil
   692  }
   693  
   694  func (p *printer) writeEnd(name Name) error {
   695  	if name.Local == "" {
   696  		return fmt.Errorf("xml: end tag with no name")
   697  	}
   698  	if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" {
   699  		return fmt.Errorf("xml: end tag </%s> without start tag", name.Local)
   700  	}
   701  	if top := p.tags[len(p.tags)-1]; top != name {
   702  		if top.Local != name.Local {
   703  			return fmt.Errorf("xml: end tag </%s> does not match start tag <%s>", name.Local, top.Local)
   704  		}
   705  		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)
   706  	}
   707  	p.tags = p.tags[:len(p.tags)-1]
   708  
   709  	p.writeIndent(-1)
   710  	p.WriteByte('<')
   711  	p.WriteByte('/')
   712  	p.WriteString(name.Local)
   713  	p.WriteByte('>')
   714  	p.popPrefix()
   715  	return nil
   716  }
   717  
   718  func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) {
   719  	switch val.Kind() {
   720  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   721  		return strconv.FormatInt(val.Int(), 10), nil, nil
   722  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   723  		return strconv.FormatUint(val.Uint(), 10), nil, nil
   724  	case reflect.Float32, reflect.Float64:
   725  		return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil
   726  	case reflect.String:
   727  		return val.String(), nil, nil
   728  	case reflect.Bool:
   729  		return strconv.FormatBool(val.Bool()), nil, nil
   730  	case reflect.Array:
   731  		if typ.Elem().Kind() != reflect.Uint8 {
   732  			break
   733  		}
   734  		// [...]byte
   735  		var bytes []byte
   736  		if val.CanAddr() {
   737  			bytes = val.Slice(0, val.Len()).Bytes()
   738  		} else {
   739  			bytes = make([]byte, val.Len())
   740  			reflect.Copy(reflect.ValueOf(bytes), val)
   741  		}
   742  		return "", bytes, nil
   743  	case reflect.Slice:
   744  		if typ.Elem().Kind() != reflect.Uint8 {
   745  			break
   746  		}
   747  		// []byte
   748  		return "", val.Bytes(), nil
   749  	}
   750  	return "", nil, &UnsupportedTypeError{typ}
   751  }
   752  
   753  var ddBytes = []byte("--")
   754  
   755  func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error {
   756  	s := parentStack{p: p}
   757  	for i := range tinfo.fields {
   758  		finfo := &tinfo.fields[i]
   759  		if finfo.flags&fAttr != 0 {
   760  			continue
   761  		}
   762  		vf := finfo.value(val)
   763  
   764  		// Dereference or skip nil pointer, interface values.
   765  		switch vf.Kind() {
   766  		case reflect.Ptr, reflect.Interface:
   767  			if !vf.IsNil() {
   768  				vf = vf.Elem()
   769  			}
   770  		}
   771  
   772  		switch finfo.flags & fMode {
   773  		case fCDATA, fCharData:
   774  			emit := EscapeText
   775  			if finfo.flags&fMode == fCDATA {
   776  				emit = emitCDATA
   777  			}
   778  			if err := s.trim(finfo.parents); err != nil {
   779  				return err
   780  			}
   781  			if vf.CanInterface() && vf.Type().Implements(textMarshalerType) {
   782  				data, err := vf.Interface().(encoding.TextMarshaler).MarshalText()
   783  				if err != nil {
   784  					return err
   785  				}
   786  				if err := emit(p, data); err != nil {
   787  					return err
   788  				}
   789  				continue
   790  			}
   791  			if vf.CanAddr() {
   792  				pv := vf.Addr()
   793  				if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
   794  					data, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
   795  					if err != nil {
   796  						return err
   797  					}
   798  					if err := emit(p, data); err != nil {
   799  						return err
   800  					}
   801  					continue
   802  				}
   803  			}
   804  			var scratch [64]byte
   805  			switch vf.Kind() {
   806  			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   807  				if err := emit(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)); err != nil {
   808  					return err
   809  				}
   810  			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   811  				if err := emit(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)); err != nil {
   812  					return err
   813  				}
   814  			case reflect.Float32, reflect.Float64:
   815  				if err := emit(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())); err != nil {
   816  					return err
   817  				}
   818  			case reflect.Bool:
   819  				if err := emit(p, strconv.AppendBool(scratch[:0], vf.Bool())); err != nil {
   820  					return err
   821  				}
   822  			case reflect.String:
   823  				if err := emit(p, []byte(vf.String())); err != nil {
   824  					return err
   825  				}
   826  			case reflect.Slice:
   827  				if elem, ok := vf.Interface().([]byte); ok {
   828  					if err := emit(p, elem); err != nil {
   829  						return err
   830  					}
   831  				}
   832  			}
   833  			continue
   834  
   835  		case fComment:
   836  			if err := s.trim(finfo.parents); err != nil {
   837  				return err
   838  			}
   839  			k := vf.Kind()
   840  			if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) {
   841  				return fmt.Errorf("xml: bad type for comment field of %s", val.Type())
   842  			}
   843  			if vf.Len() == 0 {
   844  				continue
   845  			}
   846  			p.writeIndent(0)
   847  			p.WriteString("<!--")
   848  			dashDash := false
   849  			dashLast := false
   850  			switch k {
   851  			case reflect.String:
   852  				s := vf.String()
   853  				dashDash = strings.Index(s, "--") >= 0
   854  				dashLast = s[len(s)-1] == '-'
   855  				if !dashDash {
   856  					p.WriteString(s)
   857  				}
   858  			case reflect.Slice:
   859  				b := vf.Bytes()
   860  				dashDash = bytes.Index(b, ddBytes) >= 0
   861  				dashLast = b[len(b)-1] == '-'
   862  				if !dashDash {
   863  					p.Write(b)
   864  				}
   865  			default:
   866  				panic("can't happen")
   867  			}
   868  			if dashDash {
   869  				return fmt.Errorf(`xml: comments must not contain "--"`)
   870  			}
   871  			if dashLast {
   872  				// "--->" is invalid grammar. Make it "- -->"
   873  				p.WriteByte(' ')
   874  			}
   875  			p.WriteString("-->")
   876  			continue
   877  
   878  		case fInnerXml:
   879  			iface := vf.Interface()
   880  			switch raw := iface.(type) {
   881  			case []byte:
   882  				p.Write(raw)
   883  				continue
   884  			case string:
   885  				p.WriteString(raw)
   886  				continue
   887  			}
   888  
   889  		case fElement, fElement | fAny:
   890  			if err := s.trim(finfo.parents); err != nil {
   891  				return err
   892  			}
   893  			if len(finfo.parents) > len(s.stack) {
   894  				if vf.Kind() != reflect.Ptr && vf.Kind() != reflect.Interface || !vf.IsNil() {
   895  					if err := s.push(finfo.parents[len(s.stack):]); err != nil {
   896  						return err
   897  					}
   898  				}
   899  			}
   900  		}
   901  		if err := p.marshalValue(vf, finfo, nil); err != nil {
   902  			return err
   903  		}
   904  	}
   905  	s.trim(nil)
   906  	return p.cachedWriteError()
   907  }
   908  
   909  // return the bufio Writer's cached write error
   910  func (p *printer) cachedWriteError() error {
   911  	_, err := p.Write(nil)
   912  	return err
   913  }
   914  
   915  func (p *printer) writeIndent(depthDelta int) {
   916  	if len(p.prefix) == 0 && len(p.indent) == 0 {
   917  		return
   918  	}
   919  	if depthDelta < 0 {
   920  		p.depth--
   921  		if p.indentedIn {
   922  			p.indentedIn = false
   923  			return
   924  		}
   925  		p.indentedIn = false
   926  	}
   927  	if p.putNewline {
   928  		p.WriteByte('\n')
   929  	} else {
   930  		p.putNewline = true
   931  	}
   932  	if len(p.prefix) > 0 {
   933  		p.WriteString(p.prefix)
   934  	}
   935  	if len(p.indent) > 0 {
   936  		for i := 0; i < p.depth; i++ {
   937  			p.WriteString(p.indent)
   938  		}
   939  	}
   940  	if depthDelta > 0 {
   941  		p.depth++
   942  		p.indentedIn = true
   943  	}
   944  }
   945  
   946  type parentStack struct {
   947  	p     *printer
   948  	stack []string
   949  }
   950  
   951  // trim updates the XML context to match the longest common prefix of the stack
   952  // and the given parents.  A closing tag will be written for every parent
   953  // popped.  Passing a zero slice or nil will close all the elements.
   954  func (s *parentStack) trim(parents []string) error {
   955  	split := 0
   956  	for ; split < len(parents) && split < len(s.stack); split++ {
   957  		if parents[split] != s.stack[split] {
   958  			break
   959  		}
   960  	}
   961  	for i := len(s.stack) - 1; i >= split; i-- {
   962  		if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil {
   963  			return err
   964  		}
   965  	}
   966  	s.stack = s.stack[:split]
   967  	return nil
   968  }
   969  
   970  // push adds parent elements to the stack and writes open tags.
   971  func (s *parentStack) push(parents []string) error {
   972  	for i := 0; i < len(parents); i++ {
   973  		if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil {
   974  			return err
   975  		}
   976  	}
   977  	s.stack = append(s.stack, parents...)
   978  	return nil
   979  }
   980  
   981  // A MarshalXMLError is returned when Marshal encounters a type
   982  // that cannot be converted into XML.
   983  type UnsupportedTypeError struct {
   984  	Type reflect.Type
   985  }
   986  
   987  func (e *UnsupportedTypeError) Error() string {
   988  	return "xml: unsupported type: " + e.Type.String()
   989  }
   990  
   991  func isEmptyValue(v reflect.Value) bool {
   992  	switch v.Kind() {
   993  	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
   994  		return v.Len() == 0
   995  	case reflect.Bool:
   996  		return !v.Bool()
   997  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   998  		return v.Int() == 0
   999  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1000  		return v.Uint() == 0
  1001  	case reflect.Float32, reflect.Float64:
  1002  		return v.Float() == 0
  1003  	case reflect.Interface, reflect.Ptr:
  1004  		return v.IsNil()
  1005  	}
  1006  	return false
  1007  }