Run Format

Source file src/pkg/encoding/xml/read.go

     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 xml.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 contains character data, that data is
    56	//      accumulated in the first struct field that has tag ",chardata".
    57	//      The struct field may have type []byte or string.
    58	//      If there is no such field, the character data is discarded.
    59	//
    60	//   * If the XML element contains comments, they are accumulated in
    61	//      the first struct field that has tag ",comment".  The struct
    62	//      field may have type []byte or string.  If there is no such
    63	//      field, the comments are discarded.
    64	//
    65	//   * If the XML element contains a sub-element whose name matches
    66	//      the prefix of a tag formatted as "a" or "a>b>c", unmarshal
    67	//      will descend into the XML structure looking for elements with the
    68	//      given names, and will map the innermost elements to that struct
    69	//      field. A tag starting with ">" is equivalent to one starting
    70	//      with the field name followed by ">".
    71	//
    72	//   * If the XML element contains a sub-element whose name matches
    73	//      a struct field's XMLName tag and the struct field has no
    74	//      explicit name tag as per the previous rule, unmarshal maps
    75	//      the sub-element to that struct field.
    76	//
    77	//   * If the XML element contains a sub-element whose name matches a
    78	//      field without any mode flags (",attr", ",chardata", etc), Unmarshal
    79	//      maps the sub-element to that struct field.
    80	//
    81	//   * If the XML element contains a sub-element that hasn't matched any
    82	//      of the above rules and the struct has a field with tag ",any",
    83	//      unmarshal maps the sub-element to that struct field.
    84	//
    85	//   * An anonymous struct field is handled as if the fields of its
    86	//      value were part of the outer struct.
    87	//
    88	//   * A struct field with tag "-" is never unmarshalled into.
    89	//
    90	// Unmarshal maps an XML element to a string or []byte by saving the
    91	// concatenation of that element's character data in the string or
    92	// []byte. The saved []byte is never nil.
    93	//
    94	// Unmarshal maps an attribute value to a string or []byte by saving
    95	// the value in the string or slice.
    96	//
    97	// Unmarshal maps an XML element to a slice by extending the length of
    98	// the slice and mapping the element to the newly created value.
    99	//
   100	// Unmarshal maps an XML element or attribute value to a bool by
   101	// setting it to the boolean value represented by the string.
   102	//
   103	// Unmarshal maps an XML element or attribute value to an integer or
   104	// floating-point field by setting the field to the result of
   105	// interpreting the string value in decimal.  There is no check for
   106	// overflow.
   107	//
   108	// Unmarshal maps an XML element to an xml.Name by recording the
   109	// element name.
   110	//
   111	// Unmarshal maps an XML element to a pointer by setting the pointer
   112	// to a freshly allocated value and then mapping the element to that value.
   113	//
   114	func Unmarshal(data []byte, v interface{}) error {
   115		return NewDecoder(bytes.NewBuffer(data)).Decode(v)
   116	}
   117	
   118	// Decode works like xml.Unmarshal, except it reads the decoder
   119	// stream to find the start element.
   120	func (d *Decoder) Decode(v interface{}) error {
   121		return d.DecodeElement(v, nil)
   122	}
   123	
   124	// DecodeElement works like xml.Unmarshal except that it takes
   125	// a pointer to the start XML element to decode into v.
   126	// It is useful when a client reads some raw XML tokens itself
   127	// but also wants to defer to Unmarshal for some elements.
   128	func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error {
   129		val := reflect.ValueOf(v)
   130		if val.Kind() != reflect.Ptr {
   131			return errors.New("non-pointer passed to Unmarshal")
   132		}
   133		return d.unmarshal(val.Elem(), start)
   134	}
   135	
   136	// An UnmarshalError represents an error in the unmarshalling process.
   137	type UnmarshalError string
   138	
   139	func (e UnmarshalError) Error() string { return string(e) }
   140	
   141	// Unmarshaler is the interface implemented by objects that can unmarshal
   142	// an XML element description of themselves.
   143	//
   144	// UnmarshalXML decodes a single XML element
   145	// beginning with the given start element.
   146	// If it returns an error, the outer call to Unmarshal stops and
   147	// returns that error.
   148	// UnmarshalXML must consume exactly one XML element.
   149	// One common implementation strategy is to unmarshal into
   150	// a separate value with a layout matching the expected XML
   151	// using d.DecodeElement,  and then to copy the data from
   152	// that value into the receiver.
   153	// Another common strategy is to use d.Token to process the
   154	// XML object one token at a time.
   155	// UnmarshalXML may not use d.RawToken.
   156	type Unmarshaler interface {
   157		UnmarshalXML(d *Decoder, start StartElement) error
   158	}
   159	
   160	// UnmarshalerAttr is the interface implemented by objects that can unmarshal
   161	// an XML attribute description of themselves.
   162	//
   163	// UnmarshalXMLAttr decodes a single XML attribute.
   164	// If it returns an error, the outer call to Unmarshal stops and
   165	// returns that error.
   166	// UnmarshalXMLAttr is used only for struct fields with the
   167	// "attr" option in the field tag.
   168	type UnmarshalerAttr interface {
   169		UnmarshalXMLAttr(attr Attr) error
   170	}
   171	
   172	// receiverType returns the receiver type to use in an expression like "%s.MethodName".
   173	func receiverType(val interface{}) string {
   174		t := reflect.TypeOf(val)
   175		if t.Name() != "" {
   176			return t.String()
   177		}
   178		return "(" + t.String() + ")"
   179	}
   180	
   181	// unmarshalInterface unmarshals a single XML element into val.
   182	// start is the opening tag of the element.
   183	func (p *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error {
   184		// Record that decoder must stop at end tag corresponding to start.
   185		p.pushEOF()
   186	
   187		p.unmarshalDepth++
   188		err := val.UnmarshalXML(p, *start)
   189		p.unmarshalDepth--
   190		if err != nil {
   191			p.popEOF()
   192			return err
   193		}
   194	
   195		if !p.popEOF() {
   196			return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local)
   197		}
   198	
   199		return nil
   200	}
   201	
   202	// unmarshalTextInterface unmarshals a single XML element into val.
   203	// The chardata contained in the element (but not its children)
   204	// is passed to the text unmarshaler.
   205	func (p *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler, start *StartElement) error {
   206		var buf []byte
   207		depth := 1
   208		for depth > 0 {
   209			t, err := p.Token()
   210			if err != nil {
   211				return err
   212			}
   213			switch t := t.(type) {
   214			case CharData:
   215				if depth == 1 {
   216					buf = append(buf, t...)
   217				}
   218			case StartElement:
   219				depth++
   220			case EndElement:
   221				depth--
   222			}
   223		}
   224		return val.UnmarshalText(buf)
   225	}
   226	
   227	// unmarshalAttr unmarshals a single XML attribute into val.
   228	func (p *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error {
   229		if val.Kind() == reflect.Ptr {
   230			if val.IsNil() {
   231				val.Set(reflect.New(val.Type().Elem()))
   232			}
   233			val = val.Elem()
   234		}
   235	
   236		if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) {
   237			// This is an unmarshaler with a non-pointer receiver,
   238			// so it's likely to be incorrect, but we do what we're told.
   239			return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
   240		}
   241		if val.CanAddr() {
   242			pv := val.Addr()
   243			if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) {
   244				return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
   245			}
   246		}
   247	
   248		// Not an UnmarshalerAttr; try encoding.TextUnmarshaler.
   249		if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
   250			// This is an unmarshaler with a non-pointer receiver,
   251			// so it's likely to be incorrect, but we do what we're told.
   252			return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
   253		}
   254		if val.CanAddr() {
   255			pv := val.Addr()
   256			if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   257				return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
   258			}
   259		}
   260	
   261		copyValue(val, []byte(attr.Value))
   262		return nil
   263	}
   264	
   265	var (
   266		unmarshalerType     = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
   267		unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem()
   268		textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
   269	)
   270	
   271	// Unmarshal a single XML element into val.
   272	func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error {
   273		// Find start element if we need it.
   274		if start == nil {
   275			for {
   276				tok, err := p.Token()
   277				if err != nil {
   278					return err
   279				}
   280				if t, ok := tok.(StartElement); ok {
   281					start = &t
   282					break
   283				}
   284			}
   285		}
   286	
   287		if val.Kind() == reflect.Ptr {
   288			if val.IsNil() {
   289				val.Set(reflect.New(val.Type().Elem()))
   290			}
   291			val = val.Elem()
   292		}
   293	
   294		if val.CanInterface() && val.Type().Implements(unmarshalerType) {
   295			// This is an unmarshaler with a non-pointer receiver,
   296			// so it's likely to be incorrect, but we do what we're told.
   297			return p.unmarshalInterface(val.Interface().(Unmarshaler), start)
   298		}
   299	
   300		if val.CanAddr() {
   301			pv := val.Addr()
   302			if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
   303				return p.unmarshalInterface(pv.Interface().(Unmarshaler), start)
   304			}
   305		}
   306	
   307		if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
   308			return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler), start)
   309		}
   310	
   311		if val.CanAddr() {
   312			pv := val.Addr()
   313			if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   314				return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler), start)
   315			}
   316		}
   317	
   318		var (
   319			data         []byte
   320			saveData     reflect.Value
   321			comment      []byte
   322			saveComment  reflect.Value
   323			saveXML      reflect.Value
   324			saveXMLIndex int
   325			saveXMLData  []byte
   326			saveAny      reflect.Value
   327			sv           reflect.Value
   328			tinfo        *typeInfo
   329			err          error
   330		)
   331	
   332		switch v := val; v.Kind() {
   333		default:
   334			return errors.New("unknown type " + v.Type().String())
   335	
   336		case reflect.Interface:
   337			// TODO: For now, simply ignore the field. In the near
   338			//       future we may choose to unmarshal the start
   339			//       element on it, if not nil.
   340			return p.Skip()
   341	
   342		case reflect.Slice:
   343			typ := v.Type()
   344			if typ.Elem().Kind() == reflect.Uint8 {
   345				// []byte
   346				saveData = v
   347				break
   348			}
   349	
   350			// Slice of element values.
   351			// Grow slice.
   352			n := v.Len()
   353			if n >= v.Cap() {
   354				ncap := 2 * n
   355				if ncap < 4 {
   356					ncap = 4
   357				}
   358				new := reflect.MakeSlice(typ, n, ncap)
   359				reflect.Copy(new, v)
   360				v.Set(new)
   361			}
   362			v.SetLen(n + 1)
   363	
   364			// Recur to read element into slice.
   365			if err := p.unmarshal(v.Index(n), start); err != nil {
   366				v.SetLen(n)
   367				return err
   368			}
   369			return nil
   370	
   371		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:
   372			saveData = v
   373	
   374		case reflect.Struct:
   375			typ := v.Type()
   376			if typ == nameType {
   377				v.Set(reflect.ValueOf(start.Name))
   378				break
   379			}
   380	
   381			sv = v
   382			tinfo, err = getTypeInfo(typ)
   383			if err != nil {
   384				return err
   385			}
   386	
   387			// Validate and assign element name.
   388			if tinfo.xmlname != nil {
   389				finfo := tinfo.xmlname
   390				if finfo.name != "" && finfo.name != start.Name.Local {
   391					return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
   392				}
   393				if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
   394					e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
   395					if start.Name.Space == "" {
   396						e += "no name space"
   397					} else {
   398						e += start.Name.Space
   399					}
   400					return UnmarshalError(e)
   401				}
   402				fv := finfo.value(sv)
   403				if _, ok := fv.Interface().(Name); ok {
   404					fv.Set(reflect.ValueOf(start.Name))
   405				}
   406			}
   407	
   408			// Assign attributes.
   409			// Also, determine whether we need to save character data or comments.
   410			for i := range tinfo.fields {
   411				finfo := &tinfo.fields[i]
   412				switch finfo.flags & fMode {
   413				case fAttr:
   414					strv := finfo.value(sv)
   415					// Look for attribute.
   416					for _, a := range start.Attr {
   417						if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
   418							if err := p.unmarshalAttr(strv, a); err != nil {
   419								return err
   420							}
   421							break
   422						}
   423					}
   424	
   425				case fCharData:
   426					if !saveData.IsValid() {
   427						saveData = finfo.value(sv)
   428					}
   429	
   430				case fComment:
   431					if !saveComment.IsValid() {
   432						saveComment = finfo.value(sv)
   433					}
   434	
   435				case fAny, fAny | fElement:
   436					if !saveAny.IsValid() {
   437						saveAny = finfo.value(sv)
   438					}
   439	
   440				case fInnerXml:
   441					if !saveXML.IsValid() {
   442						saveXML = finfo.value(sv)
   443						if p.saved == nil {
   444							saveXMLIndex = 0
   445							p.saved = new(bytes.Buffer)
   446						} else {
   447							saveXMLIndex = p.savedOffset()
   448						}
   449					}
   450				}
   451			}
   452		}
   453	
   454		// Find end element.
   455		// Process sub-elements along the way.
   456	Loop:
   457		for {
   458			var savedOffset int
   459			if saveXML.IsValid() {
   460				savedOffset = p.savedOffset()
   461			}
   462			tok, err := p.Token()
   463			if err != nil {
   464				return err
   465			}
   466			switch t := tok.(type) {
   467			case StartElement:
   468				consumed := false
   469				if sv.IsValid() {
   470					consumed, err = p.unmarshalPath(tinfo, sv, nil, &t)
   471					if err != nil {
   472						return err
   473					}
   474					if !consumed && saveAny.IsValid() {
   475						consumed = true
   476						if err := p.unmarshal(saveAny, &t); err != nil {
   477							return err
   478						}
   479					}
   480				}
   481				if !consumed {
   482					if err := p.Skip(); err != nil {
   483						return err
   484					}
   485				}
   486	
   487			case EndElement:
   488				if saveXML.IsValid() {
   489					saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset]
   490					if saveXMLIndex == 0 {
   491						p.saved = nil
   492					}
   493				}
   494				break Loop
   495	
   496			case CharData:
   497				if saveData.IsValid() {
   498					data = append(data, t...)
   499				}
   500	
   501			case Comment:
   502				if saveComment.IsValid() {
   503					comment = append(comment, t...)
   504				}
   505			}
   506		}
   507	
   508		if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
   509			if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
   510				return err
   511			}
   512			saveData = reflect.Value{}
   513		}
   514	
   515		if saveData.IsValid() && saveData.CanAddr() {
   516			pv := saveData.Addr()
   517			if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   518				if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
   519					return err
   520				}
   521				saveData = reflect.Value{}
   522			}
   523		}
   524	
   525		if err := copyValue(saveData, data); err != nil {
   526			return err
   527		}
   528	
   529		switch t := saveComment; t.Kind() {
   530		case reflect.String:
   531			t.SetString(string(comment))
   532		case reflect.Slice:
   533			t.Set(reflect.ValueOf(comment))
   534		}
   535	
   536		switch t := saveXML; t.Kind() {
   537		case reflect.String:
   538			t.SetString(string(saveXMLData))
   539		case reflect.Slice:
   540			t.Set(reflect.ValueOf(saveXMLData))
   541		}
   542	
   543		return nil
   544	}
   545	
   546	func copyValue(dst reflect.Value, src []byte) (err error) {
   547		dst0 := dst
   548	
   549		if dst.Kind() == reflect.Ptr {
   550			if dst.IsNil() {
   551				dst.Set(reflect.New(dst.Type().Elem()))
   552			}
   553			dst = dst.Elem()
   554		}
   555	
   556		// Save accumulated data.
   557		switch dst.Kind() {
   558		case reflect.Invalid:
   559			// Probably a comment.
   560		default:
   561			return errors.New("cannot unmarshal into " + dst0.Type().String())
   562		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   563			itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits())
   564			if err != nil {
   565				return err
   566			}
   567			dst.SetInt(itmp)
   568		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   569			utmp, err := strconv.ParseUint(string(src), 10, dst.Type().Bits())
   570			if err != nil {
   571				return err
   572			}
   573			dst.SetUint(utmp)
   574		case reflect.Float32, reflect.Float64:
   575			ftmp, err := strconv.ParseFloat(string(src), dst.Type().Bits())
   576			if err != nil {
   577				return err
   578			}
   579			dst.SetFloat(ftmp)
   580		case reflect.Bool:
   581			value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
   582			if err != nil {
   583				return err
   584			}
   585			dst.SetBool(value)
   586		case reflect.String:
   587			dst.SetString(string(src))
   588		case reflect.Slice:
   589			if len(src) == 0 {
   590				// non-nil to flag presence
   591				src = []byte{}
   592			}
   593			dst.SetBytes(src)
   594		}
   595		return nil
   596	}
   597	
   598	// unmarshalPath walks down an XML structure looking for wanted
   599	// paths, and calls unmarshal on them.
   600	// The consumed result tells whether XML elements have been consumed
   601	// from the Decoder until start's matching end element, or if it's
   602	// still untouched because start is uninteresting for sv's fields.
   603	func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) {
   604		recurse := false
   605	Loop:
   606		for i := range tinfo.fields {
   607			finfo := &tinfo.fields[i]
   608			if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
   609				continue
   610			}
   611			for j := range parents {
   612				if parents[j] != finfo.parents[j] {
   613					continue Loop
   614				}
   615			}
   616			if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
   617				// It's a perfect match, unmarshal the field.
   618				return true, p.unmarshal(finfo.value(sv), start)
   619			}
   620			if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
   621				// It's a prefix for the field. Break and recurse
   622				// since it's not ok for one field path to be itself
   623				// the prefix for another field path.
   624				recurse = true
   625	
   626				// We can reuse the same slice as long as we
   627				// don't try to append to it.
   628				parents = finfo.parents[:len(parents)+1]
   629				break
   630			}
   631		}
   632		if !recurse {
   633			// We have no business with this element.
   634			return false, nil
   635		}
   636		// The element is not a perfect match for any field, but one
   637		// or more fields have the path to this element as a parent
   638		// prefix. Recurse and attempt to match these.
   639		for {
   640			var tok Token
   641			tok, err = p.Token()
   642			if err != nil {
   643				return true, err
   644			}
   645			switch t := tok.(type) {
   646			case StartElement:
   647				consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t)
   648				if err != nil {
   649					return true, err
   650				}
   651				if !consumed2 {
   652					if err := p.Skip(); err != nil {
   653						return true, err
   654					}
   655				}
   656			case EndElement:
   657				return true, nil
   658			}
   659		}
   660	}
   661	
   662	// Skip reads tokens until it has consumed the end element
   663	// matching the most recent start element already consumed.
   664	// It recurs if it encounters a start element, so it can be used to
   665	// skip nested structures.
   666	// It returns nil if it finds an end element matching the start
   667	// element; otherwise it returns an error describing the problem.
   668	func (d *Decoder) Skip() error {
   669		for {
   670			tok, err := d.Token()
   671			if err != nil {
   672				return err
   673			}
   674			switch tok.(type) {
   675			case StartElement:
   676				if err := d.Skip(); err != nil {
   677					return err
   678				}
   679			case EndElement:
   680				return nil
   681			}
   682		}
   683	}

View as plain text