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.
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
21 // See package json for a textual representation more suitable
22 // to data structures.
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
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
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).
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.
42 // * If the struct has a field named XMLName of type Name,
43 // Unmarshal records the element name in that field.
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
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.
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
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.
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.
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 ">".
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.
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.
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.
90 // * An anonymous struct field is handled as if the fields of its
91 // value were part of the outer struct.
93 // * A struct field with tag "-" is never unmarshaled into.
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.
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.
104 // Unmarshal maps an attribute value to a string or []byte by saving
105 // the value in the string or slice.
107 // Unmarshal maps an attribute value to an Attr by saving the attribute,
108 // including its name, in the Attr.
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.
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.
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.
123 // Unmarshal maps an XML element to a Name by recording the element
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.
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)
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)
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")
151 return d.unmarshal(val.Elem(), start)
154 // An UnmarshalError represents an error in the unmarshaling process.
155 type UnmarshalError string
157 func (e UnmarshalError) Error() string { return string(e) }
159 // Unmarshaler is the interface implemented by objects that can unmarshal
160 // an XML element description of themselves.
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
178 // UnmarshalerAttr is the interface implemented by objects that can unmarshal
179 // an XML attribute description of themselves.
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
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)
196 return "(" + t.String() + ")"
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.
206 err := val.UnmarshalXML(d, *start)
214 return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local)
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 {
231 switch t := t.(type) {
234 buf = append(buf, t...)
242 return val.UnmarshalText(buf)
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 {
249 val.Set(reflect.New(val.Type().Elem()))
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)
260 if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) {
261 return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
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))
273 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
274 return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
278 if val.Type().Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
279 // Slice of element values.
282 val.Set(reflect.Append(val, reflect.Zero(val.Type().Elem())))
284 // Recur to read element into slice.
285 if err := d.unmarshalAttr(val.Index(n), attr); err != nil {
292 if val.Type() == attrType {
293 val.Set(reflect.ValueOf(attr))
297 return copyValue(val, []byte(attr.Value))
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()
307 // Unmarshal a single XML element into val.
308 func (d *Decoder) unmarshal(val reflect.Value, start *StartElement) error {
309 // Find start element if we need it.
312 tok, err := d.Token()
316 if t, ok := tok.(StartElement); ok {
323 // Load value from interface, but only if the result will be
324 // usefully addressable.
325 if val.Kind() == reflect.Interface && !val.IsNil() {
327 if e.Kind() == reflect.Ptr && !e.IsNil() {
332 if val.Kind() == reflect.Ptr {
334 val.Set(reflect.New(val.Type().Elem()))
339 if val.CanInterface() && val.Type().Implements(unmarshalerType) {
340 // This is an unmarshaler with a non-pointer receiver,
341 // so it's likely to be incorrect, but we do what we're told.
342 return d.unmarshalInterface(val.Interface().(Unmarshaler), start)
347 if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
348 return d.unmarshalInterface(pv.Interface().(Unmarshaler), start)
352 if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
353 return d.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler))
358 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
359 return d.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler))
365 saveData reflect.Value
367 saveComment reflect.Value
368 saveXML reflect.Value
371 saveAny reflect.Value
377 switch v := val; v.Kind() {
379 return errors.New("unknown type " + v.Type().String())
381 case reflect.Interface:
382 // TODO: For now, simply ignore the field. In the near
383 // future we may choose to unmarshal the start
384 // element on it, if not nil.
389 if typ.Elem().Kind() == reflect.Uint8 {
395 // Slice of element values.
398 v.Set(reflect.Append(val, reflect.Zero(v.Type().Elem())))
400 // Recur to read element into slice.
401 if err := d.unmarshal(v.Index(n), start); err != nil {
407 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:
413 v.Set(reflect.ValueOf(start.Name))
418 tinfo, err = getTypeInfo(typ)
423 // Validate and assign element name.
424 if tinfo.xmlname != nil {
425 finfo := tinfo.xmlname
426 if finfo.name != "" && finfo.name != start.Name.Local {
427 return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
429 if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
430 e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
431 if start.Name.Space == "" {
434 e += start.Name.Space
436 return UnmarshalError(e)
438 fv := finfo.value(sv)
439 if _, ok := fv.Interface().(Name); ok {
440 fv.Set(reflect.ValueOf(start.Name))
444 // Assign attributes.
445 for _, a := range start.Attr {
448 for i := range tinfo.fields {
449 finfo := &tinfo.fields[i]
450 switch finfo.flags & fMode {
452 strv := finfo.value(sv)
453 if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
454 if err := d.unmarshalAttr(strv, a); err != nil {
466 if !handled && any >= 0 {
467 finfo := &tinfo.fields[any]
468 strv := finfo.value(sv)
469 if err := d.unmarshalAttr(strv, a); err != nil {
475 // Determine whether we need to save character data or comments.
476 for i := range tinfo.fields {
477 finfo := &tinfo.fields[i]
478 switch finfo.flags & fMode {
479 case fCDATA, fCharData:
480 if !saveData.IsValid() {
481 saveData = finfo.value(sv)
485 if !saveComment.IsValid() {
486 saveComment = finfo.value(sv)
489 case fAny, fAny | fElement:
490 if !saveAny.IsValid() {
491 saveAny = finfo.value(sv)
495 if !saveXML.IsValid() {
496 saveXML = finfo.value(sv)
499 d.saved = new(bytes.Buffer)
501 saveXMLIndex = d.savedOffset()
509 // Process sub-elements along the way.
513 if saveXML.IsValid() {
514 savedOffset = d.savedOffset()
516 tok, err := d.Token()
520 switch t := tok.(type) {
524 consumed, err = d.unmarshalPath(tinfo, sv, nil, &t)
528 if !consumed && saveAny.IsValid() {
530 if err := d.unmarshal(saveAny, &t); err != nil {
536 if err := d.Skip(); err != nil {
542 if saveXML.IsValid() {
543 saveXMLData = d.saved.Bytes()[saveXMLIndex:savedOffset]
544 if saveXMLIndex == 0 {
551 if saveData.IsValid() {
552 data = append(data, t...)
556 if saveComment.IsValid() {
557 comment = append(comment, t...)
562 if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
563 if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
566 saveData = reflect.Value{}
569 if saveData.IsValid() && saveData.CanAddr() {
570 pv := saveData.Addr()
571 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
572 if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
575 saveData = reflect.Value{}
579 if err := copyValue(saveData, data); err != nil {
583 switch t := saveComment; t.Kind() {
585 t.SetString(string(comment))
587 t.Set(reflect.ValueOf(comment))
590 switch t := saveXML; t.Kind() {
592 t.SetString(string(saveXMLData))
594 if t.Type().Elem().Kind() == reflect.Uint8 {
595 t.Set(reflect.ValueOf(saveXMLData))
602 func copyValue(dst reflect.Value, src []byte) (err error) {
605 if dst.Kind() == reflect.Ptr {
607 dst.Set(reflect.New(dst.Type().Elem()))
612 // Save accumulated data.
614 case reflect.Invalid:
615 // Probably a comment.
617 return errors.New("cannot unmarshal into " + dst0.Type().String())
618 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
623 itmp, err := strconv.ParseInt(strings.TrimSpace(string(src)), 10, dst.Type().Bits())
628 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
633 utmp, err := strconv.ParseUint(strings.TrimSpace(string(src)), 10, dst.Type().Bits())
638 case reflect.Float32, reflect.Float64:
643 ftmp, err := strconv.ParseFloat(strings.TrimSpace(string(src)), dst.Type().Bits())
653 value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
659 dst.SetString(string(src))
662 // non-nil to flag presence
670 // unmarshalPath walks down an XML structure looking for wanted
671 // paths, and calls unmarshal on them.
672 // The consumed result tells whether XML elements have been consumed
673 // from the Decoder until start's matching end element, or if it's
674 // still untouched because start is uninteresting for sv's fields.
675 func (d *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) {
678 for i := range tinfo.fields {
679 finfo := &tinfo.fields[i]
680 if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
683 for j := range parents {
684 if parents[j] != finfo.parents[j] {
688 if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
689 // It's a perfect match, unmarshal the field.
690 return true, d.unmarshal(finfo.value(sv), start)
692 if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
693 // It's a prefix for the field. Break and recurse
694 // since it's not ok for one field path to be itself
695 // the prefix for another field path.
698 // We can reuse the same slice as long as we
699 // don't try to append to it.
700 parents = finfo.parents[:len(parents)+1]
705 // We have no business with this element.
708 // The element is not a perfect match for any field, but one
709 // or more fields have the path to this element as a parent
710 // prefix. Recurse and attempt to match these.
717 switch t := tok.(type) {
719 consumed2, err := d.unmarshalPath(tinfo, sv, parents, &t)
724 if err := d.Skip(); err != nil {
734 // Skip reads tokens until it has consumed the end element
735 // matching the most recent start element already consumed.
736 // It recurs if it encounters a start element, so it can be used to
737 // skip nested structures.
738 // It returns nil if it finds an end element matching the start
739 // element; otherwise it returns an error describing the problem.
740 func (d *Decoder) Skip() error {
742 tok, err := d.Token()
748 if err := d.Skip(); err != nil {