...
Run Format

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

View as plain text