...

Source file src/encoding/xml/read.go

Documentation: encoding/xml

     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 any) 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 any) 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 any, start *StartElement) error {
   147  	val := reflect.ValueOf(v)
   148  	if val.Kind() != reflect.Pointer {
   149  		return errors.New("non-pointer passed to Unmarshal")
   150  	}
   151  
   152  	if val.IsNil() {
   153  		return errors.New("nil pointer passed to Unmarshal")
   154  	}
   155  	return d.unmarshal(val.Elem(), start, 0)
   156  }
   157  
   158  // An UnmarshalError represents an error in the unmarshaling process.
   159  type UnmarshalError string
   160  
   161  func (e UnmarshalError) Error() string { return string(e) }
   162  
   163  // Unmarshaler is the interface implemented by objects that can unmarshal
   164  // an XML element description of themselves.
   165  //
   166  // UnmarshalXML decodes a single XML element
   167  // beginning with the given start element.
   168  // If it returns an error, the outer call to Unmarshal stops and
   169  // returns that error.
   170  // UnmarshalXML must consume exactly one XML element.
   171  // One common implementation strategy is to unmarshal into
   172  // a separate value with a layout matching the expected XML
   173  // using d.DecodeElement, and then to copy the data from
   174  // that value into the receiver.
   175  // Another common strategy is to use d.Token to process the
   176  // XML object one token at a time.
   177  // UnmarshalXML may not use d.RawToken.
   178  type Unmarshaler interface {
   179  	UnmarshalXML(d *Decoder, start StartElement) error
   180  }
   181  
   182  // UnmarshalerAttr is the interface implemented by objects that can unmarshal
   183  // an XML attribute description of themselves.
   184  //
   185  // UnmarshalXMLAttr decodes a single XML attribute.
   186  // If it returns an error, the outer call to Unmarshal stops and
   187  // returns that error.
   188  // UnmarshalXMLAttr is used only for struct fields with the
   189  // "attr" option in the field tag.
   190  type UnmarshalerAttr interface {
   191  	UnmarshalXMLAttr(attr Attr) error
   192  }
   193  
   194  // receiverType returns the receiver type to use in an expression like "%s.MethodName".
   195  func receiverType(val any) string {
   196  	t := reflect.TypeOf(val)
   197  	if t.Name() != "" {
   198  		return t.String()
   199  	}
   200  	return "(" + t.String() + ")"
   201  }
   202  
   203  // unmarshalInterface unmarshals a single XML element into val.
   204  // start is the opening tag of the element.
   205  func (d *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error {
   206  	// Record that decoder must stop at end tag corresponding to start.
   207  	d.pushEOF()
   208  
   209  	d.unmarshalDepth++
   210  	err := val.UnmarshalXML(d, *start)
   211  	d.unmarshalDepth--
   212  	if err != nil {
   213  		d.popEOF()
   214  		return err
   215  	}
   216  
   217  	if !d.popEOF() {
   218  		return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local)
   219  	}
   220  
   221  	return nil
   222  }
   223  
   224  // unmarshalTextInterface unmarshals a single XML element into val.
   225  // The chardata contained in the element (but not its children)
   226  // is passed to the text unmarshaler.
   227  func (d *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler) error {
   228  	var buf []byte
   229  	depth := 1
   230  	for depth > 0 {
   231  		t, err := d.Token()
   232  		if err != nil {
   233  			return err
   234  		}
   235  		switch t := t.(type) {
   236  		case CharData:
   237  			if depth == 1 {
   238  				buf = append(buf, t...)
   239  			}
   240  		case StartElement:
   241  			depth++
   242  		case EndElement:
   243  			depth--
   244  		}
   245  	}
   246  	return val.UnmarshalText(buf)
   247  }
   248  
   249  // unmarshalAttr unmarshals a single XML attribute into val.
   250  func (d *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error {
   251  	if val.Kind() == reflect.Pointer {
   252  		if val.IsNil() {
   253  			val.Set(reflect.New(val.Type().Elem()))
   254  		}
   255  		val = val.Elem()
   256  	}
   257  	if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) {
   258  		// This is an unmarshaler with a non-pointer receiver,
   259  		// so it's likely to be incorrect, but we do what we're told.
   260  		return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
   261  	}
   262  	if val.CanAddr() {
   263  		pv := val.Addr()
   264  		if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) {
   265  			return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
   266  		}
   267  	}
   268  
   269  	// Not an UnmarshalerAttr; try encoding.TextUnmarshaler.
   270  	if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
   271  		// This is an unmarshaler with a non-pointer receiver,
   272  		// so it's likely to be incorrect, but we do what we're told.
   273  		return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
   274  	}
   275  	if val.CanAddr() {
   276  		pv := val.Addr()
   277  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   278  			return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
   279  		}
   280  	}
   281  
   282  	if val.Type().Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
   283  		// Slice of element values.
   284  		// Grow slice.
   285  		n := val.Len()
   286  		val.Set(reflect.Append(val, reflect.Zero(val.Type().Elem())))
   287  
   288  		// Recur to read element into slice.
   289  		if err := d.unmarshalAttr(val.Index(n), attr); err != nil {
   290  			val.SetLen(n)
   291  			return err
   292  		}
   293  		return nil
   294  	}
   295  
   296  	if val.Type() == attrType {
   297  		val.Set(reflect.ValueOf(attr))
   298  		return nil
   299  	}
   300  
   301  	return copyValue(val, []byte(attr.Value))
   302  }
   303  
   304  var (
   305  	attrType            = reflect.TypeOf(Attr{})
   306  	unmarshalerType     = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
   307  	unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem()
   308  	textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
   309  )
   310  
   311  const maxUnmarshalDepth = 10000
   312  
   313  var errExeceededMaxUnmarshalDepth = errors.New("exceeded max depth")
   314  
   315  // Unmarshal a single XML element into val.
   316  func (d *Decoder) unmarshal(val reflect.Value, start *StartElement, depth int) error {
   317  	if depth >= maxUnmarshalDepth {
   318  		return errExeceededMaxUnmarshalDepth
   319  	}
   320  	// Find start element if we need it.
   321  	if start == nil {
   322  		for {
   323  			tok, err := d.Token()
   324  			if err != nil {
   325  				return err
   326  			}
   327  			if t, ok := tok.(StartElement); ok {
   328  				start = &t
   329  				break
   330  			}
   331  		}
   332  	}
   333  
   334  	// Load value from interface, but only if the result will be
   335  	// usefully addressable.
   336  	if val.Kind() == reflect.Interface && !val.IsNil() {
   337  		e := val.Elem()
   338  		if e.Kind() == reflect.Pointer && !e.IsNil() {
   339  			val = e
   340  		}
   341  	}
   342  
   343  	if val.Kind() == reflect.Pointer {
   344  		if val.IsNil() {
   345  			val.Set(reflect.New(val.Type().Elem()))
   346  		}
   347  		val = val.Elem()
   348  	}
   349  
   350  	if val.CanInterface() && val.Type().Implements(unmarshalerType) {
   351  		// This is an unmarshaler with a non-pointer receiver,
   352  		// so it's likely to be incorrect, but we do what we're told.
   353  		return d.unmarshalInterface(val.Interface().(Unmarshaler), start)
   354  	}
   355  
   356  	if val.CanAddr() {
   357  		pv := val.Addr()
   358  		if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
   359  			return d.unmarshalInterface(pv.Interface().(Unmarshaler), start)
   360  		}
   361  	}
   362  
   363  	if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
   364  		return d.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler))
   365  	}
   366  
   367  	if val.CanAddr() {
   368  		pv := val.Addr()
   369  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   370  			return d.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler))
   371  		}
   372  	}
   373  
   374  	var (
   375  		data         []byte
   376  		saveData     reflect.Value
   377  		comment      []byte
   378  		saveComment  reflect.Value
   379  		saveXML      reflect.Value
   380  		saveXMLIndex int
   381  		saveXMLData  []byte
   382  		saveAny      reflect.Value
   383  		sv           reflect.Value
   384  		tinfo        *typeInfo
   385  		err          error
   386  	)
   387  
   388  	switch v := val; v.Kind() {
   389  	default:
   390  		return errors.New("unknown type " + v.Type().String())
   391  
   392  	case reflect.Interface:
   393  		// TODO: For now, simply ignore the field. In the near
   394  		//       future we may choose to unmarshal the start
   395  		//       element on it, if not nil.
   396  		return d.Skip()
   397  
   398  	case reflect.Slice:
   399  		typ := v.Type()
   400  		if typ.Elem().Kind() == reflect.Uint8 {
   401  			// []byte
   402  			saveData = v
   403  			break
   404  		}
   405  
   406  		// Slice of element values.
   407  		// Grow slice.
   408  		n := v.Len()
   409  		v.Set(reflect.Append(val, reflect.Zero(v.Type().Elem())))
   410  
   411  		// Recur to read element into slice.
   412  		if err := d.unmarshal(v.Index(n), start, depth+1); err != nil {
   413  			v.SetLen(n)
   414  			return err
   415  		}
   416  		return nil
   417  
   418  	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:
   419  		saveData = v
   420  
   421  	case reflect.Struct:
   422  		typ := v.Type()
   423  		if typ == nameType {
   424  			v.Set(reflect.ValueOf(start.Name))
   425  			break
   426  		}
   427  
   428  		sv = v
   429  		tinfo, err = getTypeInfo(typ)
   430  		if err != nil {
   431  			return err
   432  		}
   433  
   434  		// Validate and assign element name.
   435  		if tinfo.xmlname != nil {
   436  			finfo := tinfo.xmlname
   437  			if finfo.name != "" && finfo.name != start.Name.Local {
   438  				return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
   439  			}
   440  			if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
   441  				e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
   442  				if start.Name.Space == "" {
   443  					e += "no name space"
   444  				} else {
   445  					e += start.Name.Space
   446  				}
   447  				return UnmarshalError(e)
   448  			}
   449  			fv := finfo.value(sv, initNilPointers)
   450  			if _, ok := fv.Interface().(Name); ok {
   451  				fv.Set(reflect.ValueOf(start.Name))
   452  			}
   453  		}
   454  
   455  		// Assign attributes.
   456  		for _, a := range start.Attr {
   457  			handled := false
   458  			any := -1
   459  			for i := range tinfo.fields {
   460  				finfo := &tinfo.fields[i]
   461  				switch finfo.flags & fMode {
   462  				case fAttr:
   463  					strv := finfo.value(sv, initNilPointers)
   464  					if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
   465  						if err := d.unmarshalAttr(strv, a); err != nil {
   466  							return err
   467  						}
   468  						handled = true
   469  					}
   470  
   471  				case fAny | fAttr:
   472  					if any == -1 {
   473  						any = i
   474  					}
   475  				}
   476  			}
   477  			if !handled && any >= 0 {
   478  				finfo := &tinfo.fields[any]
   479  				strv := finfo.value(sv, initNilPointers)
   480  				if err := d.unmarshalAttr(strv, a); err != nil {
   481  					return err
   482  				}
   483  			}
   484  		}
   485  
   486  		// Determine whether we need to save character data or comments.
   487  		for i := range tinfo.fields {
   488  			finfo := &tinfo.fields[i]
   489  			switch finfo.flags & fMode {
   490  			case fCDATA, fCharData:
   491  				if !saveData.IsValid() {
   492  					saveData = finfo.value(sv, initNilPointers)
   493  				}
   494  
   495  			case fComment:
   496  				if !saveComment.IsValid() {
   497  					saveComment = finfo.value(sv, initNilPointers)
   498  				}
   499  
   500  			case fAny, fAny | fElement:
   501  				if !saveAny.IsValid() {
   502  					saveAny = finfo.value(sv, initNilPointers)
   503  				}
   504  
   505  			case fInnerXML:
   506  				if !saveXML.IsValid() {
   507  					saveXML = finfo.value(sv, initNilPointers)
   508  					if d.saved == nil {
   509  						saveXMLIndex = 0
   510  						d.saved = new(bytes.Buffer)
   511  					} else {
   512  						saveXMLIndex = d.savedOffset()
   513  					}
   514  				}
   515  			}
   516  		}
   517  	}
   518  
   519  	// Find end element.
   520  	// Process sub-elements along the way.
   521  Loop:
   522  	for {
   523  		var savedOffset int
   524  		if saveXML.IsValid() {
   525  			savedOffset = d.savedOffset()
   526  		}
   527  		tok, err := d.Token()
   528  		if err != nil {
   529  			return err
   530  		}
   531  		switch t := tok.(type) {
   532  		case StartElement:
   533  			consumed := false
   534  			if sv.IsValid() {
   535  				// unmarshalPath can call unmarshal, so we need to pass the depth through so that
   536  				// we can continue to enforce the maximum recusion limit.
   537  				consumed, err = d.unmarshalPath(tinfo, sv, nil, &t, depth)
   538  				if err != nil {
   539  					return err
   540  				}
   541  				if !consumed && saveAny.IsValid() {
   542  					consumed = true
   543  					if err := d.unmarshal(saveAny, &t, depth+1); err != nil {
   544  						return err
   545  					}
   546  				}
   547  			}
   548  			if !consumed {
   549  				if err := d.Skip(); err != nil {
   550  					return err
   551  				}
   552  			}
   553  
   554  		case EndElement:
   555  			if saveXML.IsValid() {
   556  				saveXMLData = d.saved.Bytes()[saveXMLIndex:savedOffset]
   557  				if saveXMLIndex == 0 {
   558  					d.saved = nil
   559  				}
   560  			}
   561  			break Loop
   562  
   563  		case CharData:
   564  			if saveData.IsValid() {
   565  				data = append(data, t...)
   566  			}
   567  
   568  		case Comment:
   569  			if saveComment.IsValid() {
   570  				comment = append(comment, t...)
   571  			}
   572  		}
   573  	}
   574  
   575  	if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
   576  		if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
   577  			return err
   578  		}
   579  		saveData = reflect.Value{}
   580  	}
   581  
   582  	if saveData.IsValid() && saveData.CanAddr() {
   583  		pv := saveData.Addr()
   584  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   585  			if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
   586  				return err
   587  			}
   588  			saveData = reflect.Value{}
   589  		}
   590  	}
   591  
   592  	if err := copyValue(saveData, data); err != nil {
   593  		return err
   594  	}
   595  
   596  	switch t := saveComment; t.Kind() {
   597  	case reflect.String:
   598  		t.SetString(string(comment))
   599  	case reflect.Slice:
   600  		t.Set(reflect.ValueOf(comment))
   601  	}
   602  
   603  	switch t := saveXML; t.Kind() {
   604  	case reflect.String:
   605  		t.SetString(string(saveXMLData))
   606  	case reflect.Slice:
   607  		if t.Type().Elem().Kind() == reflect.Uint8 {
   608  			t.Set(reflect.ValueOf(saveXMLData))
   609  		}
   610  	}
   611  
   612  	return nil
   613  }
   614  
   615  func copyValue(dst reflect.Value, src []byte) (err error) {
   616  	dst0 := dst
   617  
   618  	if dst.Kind() == reflect.Pointer {
   619  		if dst.IsNil() {
   620  			dst.Set(reflect.New(dst.Type().Elem()))
   621  		}
   622  		dst = dst.Elem()
   623  	}
   624  
   625  	// Save accumulated data.
   626  	switch dst.Kind() {
   627  	case reflect.Invalid:
   628  		// Probably a comment.
   629  	default:
   630  		return errors.New("cannot unmarshal into " + dst0.Type().String())
   631  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   632  		if len(src) == 0 {
   633  			dst.SetInt(0)
   634  			return nil
   635  		}
   636  		itmp, err := strconv.ParseInt(strings.TrimSpace(string(src)), 10, dst.Type().Bits())
   637  		if err != nil {
   638  			return err
   639  		}
   640  		dst.SetInt(itmp)
   641  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   642  		if len(src) == 0 {
   643  			dst.SetUint(0)
   644  			return nil
   645  		}
   646  		utmp, err := strconv.ParseUint(strings.TrimSpace(string(src)), 10, dst.Type().Bits())
   647  		if err != nil {
   648  			return err
   649  		}
   650  		dst.SetUint(utmp)
   651  	case reflect.Float32, reflect.Float64:
   652  		if len(src) == 0 {
   653  			dst.SetFloat(0)
   654  			return nil
   655  		}
   656  		ftmp, err := strconv.ParseFloat(strings.TrimSpace(string(src)), dst.Type().Bits())
   657  		if err != nil {
   658  			return err
   659  		}
   660  		dst.SetFloat(ftmp)
   661  	case reflect.Bool:
   662  		if len(src) == 0 {
   663  			dst.SetBool(false)
   664  			return nil
   665  		}
   666  		value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
   667  		if err != nil {
   668  			return err
   669  		}
   670  		dst.SetBool(value)
   671  	case reflect.String:
   672  		dst.SetString(string(src))
   673  	case reflect.Slice:
   674  		if len(src) == 0 {
   675  			// non-nil to flag presence
   676  			src = []byte{}
   677  		}
   678  		dst.SetBytes(src)
   679  	}
   680  	return nil
   681  }
   682  
   683  // unmarshalPath walks down an XML structure looking for wanted
   684  // paths, and calls unmarshal on them.
   685  // The consumed result tells whether XML elements have been consumed
   686  // from the Decoder until start's matching end element, or if it's
   687  // still untouched because start is uninteresting for sv's fields.
   688  func (d *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement, depth int) (consumed bool, err error) {
   689  	recurse := false
   690  Loop:
   691  	for i := range tinfo.fields {
   692  		finfo := &tinfo.fields[i]
   693  		if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
   694  			continue
   695  		}
   696  		for j := range parents {
   697  			if parents[j] != finfo.parents[j] {
   698  				continue Loop
   699  			}
   700  		}
   701  		if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
   702  			// It's a perfect match, unmarshal the field.
   703  			return true, d.unmarshal(finfo.value(sv, initNilPointers), start, depth+1)
   704  		}
   705  		if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
   706  			// It's a prefix for the field. Break and recurse
   707  			// since it's not ok for one field path to be itself
   708  			// the prefix for another field path.
   709  			recurse = true
   710  
   711  			// We can reuse the same slice as long as we
   712  			// don't try to append to it.
   713  			parents = finfo.parents[:len(parents)+1]
   714  			break
   715  		}
   716  	}
   717  	if !recurse {
   718  		// We have no business with this element.
   719  		return false, nil
   720  	}
   721  	// The element is not a perfect match for any field, but one
   722  	// or more fields have the path to this element as a parent
   723  	// prefix. Recurse and attempt to match these.
   724  	for {
   725  		var tok Token
   726  		tok, err = d.Token()
   727  		if err != nil {
   728  			return true, err
   729  		}
   730  		switch t := tok.(type) {
   731  		case StartElement:
   732  			// the recursion depth of unmarshalPath is limited to the path length specified
   733  			// by the struct field tag, so we don't increment the depth here.
   734  			consumed2, err := d.unmarshalPath(tinfo, sv, parents, &t, depth)
   735  			if err != nil {
   736  				return true, err
   737  			}
   738  			if !consumed2 {
   739  				if err := d.Skip(); err != nil {
   740  					return true, err
   741  				}
   742  			}
   743  		case EndElement:
   744  			return true, nil
   745  		}
   746  	}
   747  }
   748  
   749  // Skip reads tokens until it has consumed the end element
   750  // matching the most recent start element already consumed,
   751  // skipping nested structures.
   752  // It returns nil if it finds an end element matching the start
   753  // element; otherwise it returns an error describing the problem.
   754  func (d *Decoder) Skip() error {
   755  	var depth int64
   756  	for {
   757  		tok, err := d.Token()
   758  		if err != nil {
   759  			return err
   760  		}
   761  		switch tok.(type) {
   762  		case StartElement:
   763  			depth++
   764  		case EndElement:
   765  			if depth == 0 {
   766  				return nil
   767  			}
   768  			depth--
   769  		}
   770  	}
   771  }
   772  

View as plain text