github.com/vmware/govmomi@v0.37.2/vim25/xml/read.go (about)

     1  // Copyright 2009 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  	"bytes"
     9  	"encoding"
    10  	"errors"
    11  	"fmt"
    12  	"reflect"
    13  	"strconv"
    14  	"strings"
    15  )
    16  
    17  // BUG(rsc): Mapping between XML elements and data structures is inherently flawed:
    18  // an XML element is an order-dependent collection of anonymous
    19  // values, while a data structure is an order-independent collection
    20  // of named values.
    21  // See package json for a textual representation more suitable
    22  // to data structures.
    23  
    24  // Unmarshal parses the XML-encoded data and stores the result in
    25  // the value pointed to by v, which must be an arbitrary struct,
    26  // slice, or string. Well-formed data that does not fit into v is
    27  // discarded.
    28  //
    29  // Because Unmarshal uses the reflect package, it can only assign
    30  // to exported (upper case) fields. Unmarshal uses a case-sensitive
    31  // comparison to match XML element names to tag values and struct
    32  // field names.
    33  //
    34  // Unmarshal maps an XML element to a struct using the following rules.
    35  // In the rules, the tag of a field refers to the value associated with the
    36  // key 'xml' in the struct field's tag (see the example above).
    37  //
    38  //   * If the struct has a field of type []byte or string with tag
    39  //      ",innerxml", Unmarshal accumulates the raw XML nested inside the
    40  //      element in that field. The rest of the rules still apply.
    41  //
    42  //   * If the struct has a field named XMLName of type Name,
    43  //      Unmarshal records the element name in that field.
    44  //
    45  //   * If the XMLName field has an associated tag of the form
    46  //      "name" or "namespace-URL name", the XML element must have
    47  //      the given name (and, optionally, name space) or else Unmarshal
    48  //      returns an error.
    49  //
    50  //   * If the XML element has an attribute whose name matches a
    51  //      struct field name with an associated tag containing ",attr" or
    52  //      the explicit name in a struct field tag of the form "name,attr",
    53  //      Unmarshal records the attribute value in that field.
    54  //
    55  //   * If the XML element has an attribute not handled by the previous
    56  //      rule and the struct has a field with an associated tag containing
    57  //      ",any,attr", Unmarshal records the attribute value in the first
    58  //      such field.
    59  //
    60  //   * If the XML element contains character data, that data is
    61  //      accumulated in the first struct field that has tag ",chardata".
    62  //      The struct field may have type []byte or string.
    63  //      If there is no such field, the character data is discarded.
    64  //
    65  //   * If the XML element contains comments, they are accumulated in
    66  //      the first struct field that has tag ",comment".  The struct
    67  //      field may have type []byte or string. If there is no such
    68  //      field, the comments are discarded.
    69  //
    70  //   * If the XML element contains a sub-element whose name matches
    71  //      the prefix of a tag formatted as "a" or "a>b>c", unmarshal
    72  //      will descend into the XML structure looking for elements with the
    73  //      given names, and will map the innermost elements to that struct
    74  //      field. A tag starting with ">" is equivalent to one starting
    75  //      with the field name followed by ">".
    76  //
    77  //   * If the XML element contains a sub-element whose name matches
    78  //      a struct field's XMLName tag and the struct field has no
    79  //      explicit name tag as per the previous rule, unmarshal maps
    80  //      the sub-element to that struct field.
    81  //
    82  //   * If the XML element contains a sub-element whose name matches a
    83  //      field without any mode flags (",attr", ",chardata", etc), Unmarshal
    84  //      maps the sub-element to that struct field.
    85  //
    86  //   * If the XML element contains a sub-element that hasn't matched any
    87  //      of the above rules and the struct has a field with tag ",any",
    88  //      unmarshal maps the sub-element to that struct field.
    89  //
    90  //   * An anonymous struct field is handled as if the fields of its
    91  //      value were part of the outer struct.
    92  //
    93  //   * A struct field with tag "-" is never unmarshaled into.
    94  //
    95  // If Unmarshal encounters a field type that implements the Unmarshaler
    96  // interface, Unmarshal calls its UnmarshalXML method to produce the value from
    97  // the XML element.  Otherwise, if the value implements
    98  // encoding.TextUnmarshaler, Unmarshal calls that value's UnmarshalText method.
    99  //
   100  // Unmarshal maps an XML element to a string or []byte by saving the
   101  // concatenation of that element's character data in the string or
   102  // []byte. The saved []byte is never nil.
   103  //
   104  // Unmarshal maps an attribute value to a string or []byte by saving
   105  // the value in the string or slice.
   106  //
   107  // Unmarshal maps an attribute value to an Attr by saving the attribute,
   108  // including its name, in the Attr.
   109  //
   110  // Unmarshal maps an XML element or attribute value to a slice by
   111  // extending the length of the slice and mapping the element or attribute
   112  // to the newly created value.
   113  //
   114  // Unmarshal maps an XML element or attribute value to a bool by
   115  // setting it to the boolean value represented by the string. Whitespace
   116  // is trimmed and ignored.
   117  //
   118  // Unmarshal maps an XML element or attribute value to an integer or
   119  // floating-point field by setting the field to the result of
   120  // interpreting the string value in decimal. There is no check for
   121  // overflow. Whitespace is trimmed and ignored.
   122  //
   123  // Unmarshal maps an XML element to a Name by recording the element
   124  // name.
   125  //
   126  // Unmarshal maps an XML element to a pointer by setting the pointer
   127  // to a freshly allocated value and then mapping the element to that value.
   128  //
   129  // A missing element or empty attribute value will be unmarshaled as a zero value.
   130  // If the field is a slice, a zero value will be appended to the field. Otherwise, the
   131  // field will be set to its zero value.
   132  func Unmarshal(data []byte, v interface{}) error {
   133  	return NewDecoder(bytes.NewReader(data)).Decode(v)
   134  }
   135  
   136  // Decode works like Unmarshal, except it reads the decoder
   137  // stream to find the start element.
   138  func (d *Decoder) Decode(v interface{}) error {
   139  	return d.DecodeElement(v, nil)
   140  }
   141  
   142  // DecodeElement works like Unmarshal except that it takes
   143  // a pointer to the start XML element to decode into v.
   144  // It is useful when a client reads some raw XML tokens itself
   145  // but also wants to defer to Unmarshal for some elements.
   146  func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error {
   147  	val := reflect.ValueOf(v)
   148  	if val.Kind() != reflect.Ptr {
   149  		return errors.New("non-pointer passed to Unmarshal")
   150  	}
   151  	return d.unmarshal(val.Elem(), start)
   152  }
   153  
   154  // An UnmarshalError represents an error in the unmarshaling process.
   155  type UnmarshalError string
   156  
   157  func (e UnmarshalError) Error() string { return string(e) }
   158  
   159  // Unmarshaler is the interface implemented by objects that can unmarshal
   160  // an XML element description of themselves.
   161  //
   162  // UnmarshalXML decodes a single XML element
   163  // beginning with the given start element.
   164  // If it returns an error, the outer call to Unmarshal stops and
   165  // returns that error.
   166  // UnmarshalXML must consume exactly one XML element.
   167  // One common implementation strategy is to unmarshal into
   168  // a separate value with a layout matching the expected XML
   169  // using d.DecodeElement, and then to copy the data from
   170  // that value into the receiver.
   171  // Another common strategy is to use d.Token to process the
   172  // XML object one token at a time.
   173  // UnmarshalXML may not use d.RawToken.
   174  type Unmarshaler interface {
   175  	UnmarshalXML(d *Decoder, start StartElement) error
   176  }
   177  
   178  // UnmarshalerAttr is the interface implemented by objects that can unmarshal
   179  // an XML attribute description of themselves.
   180  //
   181  // UnmarshalXMLAttr decodes a single XML attribute.
   182  // If it returns an error, the outer call to Unmarshal stops and
   183  // returns that error.
   184  // UnmarshalXMLAttr is used only for struct fields with the
   185  // "attr" option in the field tag.
   186  type UnmarshalerAttr interface {
   187  	UnmarshalXMLAttr(attr Attr) error
   188  }
   189  
   190  // receiverType returns the receiver type to use in an expression like "%s.MethodName".
   191  func receiverType(val interface{}) string {
   192  	t := reflect.TypeOf(val)
   193  	if t.Name() != "" {
   194  		return t.String()
   195  	}
   196  	return "(" + t.String() + ")"
   197  }
   198  
   199  // unmarshalInterface unmarshals a single XML element into val.
   200  // start is the opening tag of the element.
   201  func (d *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error {
   202  	// Record that decoder must stop at end tag corresponding to start.
   203  	d.pushEOF()
   204  
   205  	d.unmarshalDepth++
   206  	err := val.UnmarshalXML(d, *start)
   207  	d.unmarshalDepth--
   208  	if err != nil {
   209  		d.popEOF()
   210  		return err
   211  	}
   212  
   213  	if !d.popEOF() {
   214  		return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local)
   215  	}
   216  
   217  	return nil
   218  }
   219  
   220  // unmarshalTextInterface unmarshals a single XML element into val.
   221  // The chardata contained in the element (but not its children)
   222  // is passed to the text unmarshaler.
   223  func (d *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler) error {
   224  	var buf []byte
   225  	depth := 1
   226  	for depth > 0 {
   227  		t, err := d.Token()
   228  		if err != nil {
   229  			return err
   230  		}
   231  		switch t := t.(type) {
   232  		case CharData:
   233  			if depth == 1 {
   234  				buf = append(buf, t...)
   235  			}
   236  		case StartElement:
   237  			depth++
   238  		case EndElement:
   239  			depth--
   240  		}
   241  	}
   242  	return val.UnmarshalText(buf)
   243  }
   244  
   245  // unmarshalAttr unmarshals a single XML attribute into val.
   246  func (d *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error {
   247  	if val.Kind() == reflect.Ptr {
   248  		if val.IsNil() {
   249  			val.Set(reflect.New(val.Type().Elem()))
   250  		}
   251  		val = val.Elem()
   252  	}
   253  	if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) {
   254  		// This is an unmarshaler with a non-pointer receiver,
   255  		// so it's likely to be incorrect, but we do what we're told.
   256  		return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
   257  	}
   258  	if val.CanAddr() {
   259  		pv := val.Addr()
   260  		if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) {
   261  			return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
   262  		}
   263  	}
   264  
   265  	// Not an UnmarshalerAttr; try encoding.TextUnmarshaler.
   266  	if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
   267  		// This is an unmarshaler with a non-pointer receiver,
   268  		// so it's likely to be incorrect, but we do what we're told.
   269  		return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
   270  	}
   271  	if val.CanAddr() {
   272  		pv := val.Addr()
   273  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   274  			return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
   275  		}
   276  	}
   277  
   278  	if val.Type().Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
   279  		// Slice of element values.
   280  		// Grow slice.
   281  		n := val.Len()
   282  		val.Set(reflect.Append(val, reflect.Zero(val.Type().Elem())))
   283  
   284  		// Recur to read element into slice.
   285  		if err := d.unmarshalAttr(val.Index(n), attr); err != nil {
   286  			val.SetLen(n)
   287  			return err
   288  		}
   289  		return nil
   290  	}
   291  
   292  	if val.Type() == attrType {
   293  		val.Set(reflect.ValueOf(attr))
   294  		return nil
   295  	}
   296  
   297  	return copyValue(val, []byte(attr.Value))
   298  }
   299  
   300  var (
   301  	attrType            = reflect.TypeOf(Attr{})
   302  	unmarshalerType     = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
   303  	unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem()
   304  	textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
   305  )
   306  
   307  // Find reflect.Type for an element's type attribute.
   308  func (p *Decoder) typeForElement(val reflect.Value, start *StartElement) reflect.Type {
   309  	t := ""
   310  	for _, a := range start.Attr {
   311  		if a.Name == xmlSchemaInstance || a.Name == xsiType {
   312  			t = a.Value
   313  			break
   314  		}
   315  	}
   316  
   317  	if t == "" {
   318  		// No type attribute; fall back to looking up type by interface name.
   319  		t = val.Type().Name()
   320  	}
   321  
   322  	// Maybe the type is a basic xsd:* type.
   323  	typ := stringToType(t)
   324  	if typ != nil {
   325  		return typ
   326  	}
   327  
   328  	// Maybe the type is a custom type.
   329  	if p.TypeFunc != nil {
   330  		if typ, ok := p.TypeFunc(t); ok {
   331  			return typ
   332  		}
   333  	}
   334  
   335  	return nil
   336  }
   337  
   338  // Unmarshal a single XML element into val.
   339  func (d *Decoder) unmarshal(val reflect.Value, start *StartElement) error {
   340  	// Find start element if we need it.
   341  	if start == nil {
   342  		for {
   343  			tok, err := d.Token()
   344  			if err != nil {
   345  				return err
   346  			}
   347  			if t, ok := tok.(StartElement); ok {
   348  				start = &t
   349  				break
   350  			}
   351  		}
   352  	}
   353  
   354  	// Try to figure out type for empty interface values.
   355  	if val.Kind() == reflect.Interface && val.IsNil() {
   356  		typ := d.typeForElement(val, start)
   357  		if typ != nil {
   358  			pval := reflect.New(typ).Elem()
   359  			err := d.unmarshal(pval, start)
   360  			if err != nil {
   361  				return err
   362  			}
   363  
   364  			for i := 0; i < 2; i++ {
   365  				if typ.Implements(val.Type()) {
   366  					val.Set(pval)
   367  					return nil
   368  				}
   369  
   370  				typ = reflect.PtrTo(typ)
   371  				pval = pval.Addr()
   372  			}
   373  
   374  			val.Set(pval)
   375  			return nil
   376  		}
   377  	}
   378  
   379  	// Load value from interface, but only if the result will be
   380  	// usefully addressable.
   381  	if val.Kind() == reflect.Interface && !val.IsNil() {
   382  		e := val.Elem()
   383  		if e.Kind() == reflect.Ptr && !e.IsNil() {
   384  			val = e
   385  		}
   386  	}
   387  
   388  	if val.Kind() == reflect.Ptr {
   389  		if val.IsNil() {
   390  			val.Set(reflect.New(val.Type().Elem()))
   391  		}
   392  		val = val.Elem()
   393  	}
   394  
   395  	if val.CanInterface() && val.Type().Implements(unmarshalerType) {
   396  		// This is an unmarshaler with a non-pointer receiver,
   397  		// so it's likely to be incorrect, but we do what we're told.
   398  		return d.unmarshalInterface(val.Interface().(Unmarshaler), start)
   399  	}
   400  
   401  	if val.CanAddr() {
   402  		pv := val.Addr()
   403  		if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
   404  			return d.unmarshalInterface(pv.Interface().(Unmarshaler), start)
   405  		}
   406  	}
   407  
   408  	if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
   409  		return d.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler))
   410  	}
   411  
   412  	if val.CanAddr() {
   413  		pv := val.Addr()
   414  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   415  			return d.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler))
   416  		}
   417  	}
   418  
   419  	var (
   420  		data         []byte
   421  		saveData     reflect.Value
   422  		comment      []byte
   423  		saveComment  reflect.Value
   424  		saveXML      reflect.Value
   425  		saveXMLIndex int
   426  		saveXMLData  []byte
   427  		saveAny      reflect.Value
   428  		sv           reflect.Value
   429  		tinfo        *typeInfo
   430  		err          error
   431  	)
   432  
   433  	switch v := val; v.Kind() {
   434  	default:
   435  		return errors.New("unknown type " + v.Type().String())
   436  
   437  	case reflect.Interface:
   438  		// TODO: For now, simply ignore the field. In the near
   439  		//       future we may choose to unmarshal the start
   440  		//       element on it, if not nil.
   441  		return d.Skip()
   442  
   443  	case reflect.Slice:
   444  		typ := v.Type()
   445  		if typ.Elem().Kind() == reflect.Uint8 {
   446  			// []byte
   447  			saveData = v
   448  			break
   449  		}
   450  
   451  		// Slice of element values.
   452  		// Grow slice.
   453  		n := v.Len()
   454  		v.Set(reflect.Append(val, reflect.Zero(v.Type().Elem())))
   455  
   456  		// Recur to read element into slice.
   457  		if err := d.unmarshal(v.Index(n), start); err != nil {
   458  			v.SetLen(n)
   459  			return err
   460  		}
   461  		return nil
   462  
   463  	case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.String:
   464  		saveData = v
   465  
   466  	case reflect.Struct:
   467  		typ := v.Type()
   468  		if typ == nameType {
   469  			v.Set(reflect.ValueOf(start.Name))
   470  			break
   471  		}
   472  
   473  		sv = v
   474  		tinfo, err = getTypeInfo(typ)
   475  		if err != nil {
   476  			return err
   477  		}
   478  
   479  		// Validate and assign element name.
   480  		if tinfo.xmlname != nil {
   481  			finfo := tinfo.xmlname
   482  			if finfo.name != "" && finfo.name != start.Name.Local {
   483  				return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
   484  			}
   485  			if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
   486  				e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
   487  				if start.Name.Space == "" {
   488  					e += "no name space"
   489  				} else {
   490  					e += start.Name.Space
   491  				}
   492  				return UnmarshalError(e)
   493  			}
   494  			fv := finfo.value(sv, initNilPointers)
   495  			if _, ok := fv.Interface().(Name); ok {
   496  				fv.Set(reflect.ValueOf(start.Name))
   497  			}
   498  		}
   499  
   500  		// Assign attributes.
   501  		for _, a := range start.Attr {
   502  			handled := false
   503  			any := -1
   504  			for i := range tinfo.fields {
   505  				finfo := &tinfo.fields[i]
   506  				switch finfo.flags & fMode {
   507  				case fAttr:
   508  					strv := finfo.value(sv, initNilPointers)
   509  					if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
   510  						needTypeAttr := (finfo.flags & fTypeAttr) != 0
   511  						// HACK: avoid using xsi:type value for a "type" attribute, such as ManagedObjectReference.Type for example.
   512  						if needTypeAttr || (a.Name != xmlSchemaInstance && a.Name != xsiType) {
   513  							if err := d.unmarshalAttr(strv, a); err != nil {
   514  								return err
   515  							}
   516  						}
   517  						handled = true
   518  					}
   519  
   520  				case fAny | fAttr:
   521  					if any == -1 {
   522  						any = i
   523  					}
   524  				}
   525  			}
   526  			if !handled && any >= 0 {
   527  				finfo := &tinfo.fields[any]
   528  				strv := finfo.value(sv, initNilPointers)
   529  				if err := d.unmarshalAttr(strv, a); err != nil {
   530  					return err
   531  				}
   532  			}
   533  		}
   534  
   535  		// Determine whether we need to save character data or comments.
   536  		for i := range tinfo.fields {
   537  			finfo := &tinfo.fields[i]
   538  			switch finfo.flags & fMode {
   539  			case fCDATA, fCharData:
   540  				if !saveData.IsValid() {
   541  					saveData = finfo.value(sv, initNilPointers)
   542  				}
   543  
   544  			case fComment:
   545  				if !saveComment.IsValid() {
   546  					saveComment = finfo.value(sv, initNilPointers)
   547  				}
   548  
   549  			case fAny, fAny | fElement:
   550  				if !saveAny.IsValid() {
   551  					saveAny = finfo.value(sv, initNilPointers)
   552  				}
   553  
   554  			case fInnerXML:
   555  				if !saveXML.IsValid() {
   556  					saveXML = finfo.value(sv, initNilPointers)
   557  					if d.saved == nil {
   558  						saveXMLIndex = 0
   559  						d.saved = new(bytes.Buffer)
   560  					} else {
   561  						saveXMLIndex = d.savedOffset()
   562  					}
   563  				}
   564  			}
   565  		}
   566  	}
   567  
   568  	// Find end element.
   569  	// Process sub-elements along the way.
   570  Loop:
   571  	for {
   572  		var savedOffset int
   573  		if saveXML.IsValid() {
   574  			savedOffset = d.savedOffset()
   575  		}
   576  		tok, err := d.Token()
   577  		if err != nil {
   578  			return err
   579  		}
   580  		switch t := tok.(type) {
   581  		case StartElement:
   582  			consumed := false
   583  			if sv.IsValid() {
   584  				consumed, err = d.unmarshalPath(tinfo, sv, nil, &t)
   585  				if err != nil {
   586  					return err
   587  				}
   588  				if !consumed && saveAny.IsValid() {
   589  					consumed = true
   590  					if err := d.unmarshal(saveAny, &t); err != nil {
   591  						return err
   592  					}
   593  				}
   594  			}
   595  			if !consumed {
   596  				if err := d.Skip(); err != nil {
   597  					return err
   598  				}
   599  			}
   600  
   601  		case EndElement:
   602  			if saveXML.IsValid() {
   603  				saveXMLData = d.saved.Bytes()[saveXMLIndex:savedOffset]
   604  				if saveXMLIndex == 0 {
   605  					d.saved = nil
   606  				}
   607  			}
   608  			break Loop
   609  
   610  		case CharData:
   611  			if saveData.IsValid() {
   612  				data = append(data, t...)
   613  			}
   614  
   615  		case Comment:
   616  			if saveComment.IsValid() {
   617  				comment = append(comment, t...)
   618  			}
   619  		}
   620  	}
   621  
   622  	if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
   623  		if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
   624  			return err
   625  		}
   626  		saveData = reflect.Value{}
   627  	}
   628  
   629  	if saveData.IsValid() && saveData.CanAddr() {
   630  		pv := saveData.Addr()
   631  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   632  			if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
   633  				return err
   634  			}
   635  			saveData = reflect.Value{}
   636  		}
   637  	}
   638  
   639  	if err := copyValue(saveData, data); err != nil {
   640  		return err
   641  	}
   642  
   643  	switch t := saveComment; t.Kind() {
   644  	case reflect.String:
   645  		t.SetString(string(comment))
   646  	case reflect.Slice:
   647  		t.Set(reflect.ValueOf(comment))
   648  	}
   649  
   650  	switch t := saveXML; t.Kind() {
   651  	case reflect.String:
   652  		t.SetString(string(saveXMLData))
   653  	case reflect.Slice:
   654  		if t.Type().Elem().Kind() == reflect.Uint8 {
   655  			t.Set(reflect.ValueOf(saveXMLData))
   656  		}
   657  	}
   658  
   659  	return nil
   660  }
   661  
   662  func copyValue(dst reflect.Value, src []byte) (err error) {
   663  	dst0 := dst
   664  
   665  	if dst.Kind() == reflect.Ptr {
   666  		if dst.IsNil() {
   667  			dst.Set(reflect.New(dst.Type().Elem()))
   668  		}
   669  		dst = dst.Elem()
   670  	}
   671  
   672  	// Save accumulated data.
   673  	switch dst.Kind() {
   674  	case reflect.Invalid:
   675  		// Probably a comment.
   676  	default:
   677  		return errors.New("cannot unmarshal into " + dst0.Type().String())
   678  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   679  		if len(src) == 0 {
   680  			dst.SetInt(0)
   681  			return nil
   682  		}
   683  		itmp, err := strconv.ParseInt(strings.TrimSpace(string(src)), 10, dst.Type().Bits())
   684  		if err != nil {
   685  			return err
   686  		}
   687  		dst.SetInt(itmp)
   688  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   689  		var utmp uint64
   690  		if len(src) > 0 && src[0] == '-' {
   691  			// Negative value for unsigned field.
   692  			// Assume it was serialized following two's complement.
   693  			itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits())
   694  			if err != nil {
   695  				return err
   696  			}
   697  			// Reinterpret value based on type width.
   698  			switch dst.Type().Bits() {
   699  			case 8:
   700  				utmp = uint64(uint8(itmp))
   701  			case 16:
   702  				utmp = uint64(uint16(itmp))
   703  			case 32:
   704  				utmp = uint64(uint32(itmp))
   705  			case 64:
   706  				utmp = uint64(uint64(itmp))
   707  			}
   708  		} else {
   709  			if len(src) == 0 {
   710  				dst.SetUint(0)
   711  				return nil
   712  			}
   713  
   714  			utmp, err = strconv.ParseUint(strings.TrimSpace(string(src)), 10, dst.Type().Bits())
   715  			if err != nil {
   716  				return err
   717  			}
   718  		}
   719  		dst.SetUint(utmp)
   720  	case reflect.Float32, reflect.Float64:
   721  		if len(src) == 0 {
   722  			dst.SetFloat(0)
   723  			return nil
   724  		}
   725  		ftmp, err := strconv.ParseFloat(strings.TrimSpace(string(src)), dst.Type().Bits())
   726  		if err != nil {
   727  			return err
   728  		}
   729  		dst.SetFloat(ftmp)
   730  	case reflect.Bool:
   731  		if len(src) == 0 {
   732  			dst.SetBool(false)
   733  			return nil
   734  		}
   735  		value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
   736  		if err != nil {
   737  			return err
   738  		}
   739  		dst.SetBool(value)
   740  	case reflect.String:
   741  		dst.SetString(string(src))
   742  	case reflect.Slice:
   743  		if len(src) == 0 {
   744  			// non-nil to flag presence
   745  			src = []byte{}
   746  		}
   747  		dst.SetBytes(src)
   748  	}
   749  	return nil
   750  }
   751  
   752  // unmarshalPath walks down an XML structure looking for wanted
   753  // paths, and calls unmarshal on them.
   754  // The consumed result tells whether XML elements have been consumed
   755  // from the Decoder until start's matching end element, or if it's
   756  // still untouched because start is uninteresting for sv's fields.
   757  func (d *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) {
   758  	recurse := false
   759  Loop:
   760  	for i := range tinfo.fields {
   761  		finfo := &tinfo.fields[i]
   762  		if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
   763  			continue
   764  		}
   765  		for j := range parents {
   766  			if parents[j] != finfo.parents[j] {
   767  				continue Loop
   768  			}
   769  		}
   770  		if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
   771  			// It's a perfect match, unmarshal the field.
   772  			return true, d.unmarshal(finfo.value(sv, initNilPointers), start)
   773  		}
   774  		if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
   775  			// It's a prefix for the field. Break and recurse
   776  			// since it's not ok for one field path to be itself
   777  			// the prefix for another field path.
   778  			recurse = true
   779  
   780  			// We can reuse the same slice as long as we
   781  			// don't try to append to it.
   782  			parents = finfo.parents[:len(parents)+1]
   783  			break
   784  		}
   785  	}
   786  	if !recurse {
   787  		// We have no business with this element.
   788  		return false, nil
   789  	}
   790  	// The element is not a perfect match for any field, but one
   791  	// or more fields have the path to this element as a parent
   792  	// prefix. Recurse and attempt to match these.
   793  	for {
   794  		var tok Token
   795  		tok, err = d.Token()
   796  		if err != nil {
   797  			return true, err
   798  		}
   799  		switch t := tok.(type) {
   800  		case StartElement:
   801  			consumed2, err := d.unmarshalPath(tinfo, sv, parents, &t)
   802  			if err != nil {
   803  				return true, err
   804  			}
   805  			if !consumed2 {
   806  				if err := d.Skip(); err != nil {
   807  					return true, err
   808  				}
   809  			}
   810  		case EndElement:
   811  			return true, nil
   812  		}
   813  	}
   814  }
   815  
   816  // Skip reads tokens until it has consumed the end element
   817  // matching the most recent start element already consumed.
   818  // It recurs if it encounters a start element, so it can be used to
   819  // skip nested structures.
   820  // It returns nil if it finds an end element matching the start
   821  // element; otherwise it returns an error describing the problem.
   822  func (d *Decoder) Skip() error {
   823  	for {
   824  		tok, err := d.Token()
   825  		if err != nil {
   826  			return err
   827  		}
   828  		switch tok.(type) {
   829  		case StartElement:
   830  			if err := d.Skip(); err != nil {
   831  				return err
   832  			}
   833  		case EndElement:
   834  			return nil
   835  		}
   836  	}
   837  }