...
Run Format

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

View as plain text