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 // Unmarshal maps an XML element to a string or []byte by saving the
96 // concatenation of that element's character data in the string or
97 // []byte. The saved []byte is never nil.
99 // Unmarshal maps an attribute value to a string or []byte by saving
100 // the value in the string or slice.
102 // Unmarshal maps an attribute value to an Attr by saving the attribute,
103 // including its name, in the Attr.
105 // Unmarshal maps an XML element or attribute value to a slice by
106 // extending the length of the slice and mapping the element or attribute
107 // to the newly created value.
109 // Unmarshal maps an XML element or attribute value to a bool by
110 // setting it to the boolean value represented by the string.
112 // Unmarshal maps an XML element or attribute value to an integer or
113 // floating-point field by setting the field to the result of
114 // interpreting the string value in decimal. There is no check for
117 // Unmarshal maps an XML element to a Name by recording the element
120 // Unmarshal maps an XML element to a pointer by setting the pointer
121 // to a freshly allocated value and then mapping the element to that value.
123 // A missing element or empty attribute value will be unmarshaled as a zero value.
124 // If the field is a slice, a zero value will be appended to the field. Otherwise, the
125 // field will be set to its zero value.
126 func Unmarshal(data
[]byte, v
interface{}) error
{
127 return NewDecoder(bytes
.NewReader(data
)).Decode(v
)
130 // Decode works like Unmarshal, except it reads the decoder
131 // stream to find the start element.
132 func (d
*Decoder
) Decode(v
interface{}) error
{
133 return d
.DecodeElement(v
, nil)
136 // DecodeElement works like Unmarshal except that it takes
137 // a pointer to the start XML element to decode into v.
138 // It is useful when a client reads some raw XML tokens itself
139 // but also wants to defer to Unmarshal for some elements.
140 func (d
*Decoder
) DecodeElement(v
interface{}, start
*StartElement
) error
{
141 val
:= reflect
.ValueOf(v
)
142 if val
.Kind() != reflect
.Ptr
{
143 return errors
.New("non-pointer passed to Unmarshal")
145 return d
.unmarshal(val
.Elem(), start
)
148 // An UnmarshalError represents an error in the unmarshaling process.
149 type UnmarshalError
string
151 func (e UnmarshalError
) Error() string { return string(e
) }
153 // Unmarshaler is the interface implemented by objects that can unmarshal
154 // an XML element description of themselves.
156 // UnmarshalXML decodes a single XML element
157 // beginning with the given start element.
158 // If it returns an error, the outer call to Unmarshal stops and
159 // returns that error.
160 // UnmarshalXML must consume exactly one XML element.
161 // One common implementation strategy is to unmarshal into
162 // a separate value with a layout matching the expected XML
163 // using d.DecodeElement, and then to copy the data from
164 // that value into the receiver.
165 // Another common strategy is to use d.Token to process the
166 // XML object one token at a time.
167 // UnmarshalXML may not use d.RawToken.
168 type Unmarshaler
interface {
169 UnmarshalXML(d
*Decoder
, start StartElement
) error
172 // UnmarshalerAttr is the interface implemented by objects that can unmarshal
173 // an XML attribute description of themselves.
175 // UnmarshalXMLAttr decodes a single XML attribute.
176 // If it returns an error, the outer call to Unmarshal stops and
177 // returns that error.
178 // UnmarshalXMLAttr is used only for struct fields with the
179 // "attr" option in the field tag.
180 type UnmarshalerAttr
interface {
181 UnmarshalXMLAttr(attr Attr
) error
184 // receiverType returns the receiver type to use in an expression like "%s.MethodName".
185 func receiverType(val
interface{}) string {
186 t
:= reflect
.TypeOf(val
)
190 return "(" + t
.String() + ")"
193 // unmarshalInterface unmarshals a single XML element into val.
194 // start is the opening tag of the element.
195 func (p
*Decoder
) unmarshalInterface(val Unmarshaler
, start
*StartElement
) error
{
196 // Record that decoder must stop at end tag corresponding to start.
200 err
:= val
.UnmarshalXML(p
, *start
)
208 return fmt
.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val
), start
.Name
.Local
)
214 // unmarshalTextInterface unmarshals a single XML element into val.
215 // The chardata contained in the element (but not its children)
216 // is passed to the text unmarshaler.
217 func (p
*Decoder
) unmarshalTextInterface(val encoding
.TextUnmarshaler
) error
{
225 switch t
:= t
.(type) {
228 buf
= append(buf
, t
...)
236 return val
.UnmarshalText(buf
)
239 // unmarshalAttr unmarshals a single XML attribute into val.
240 func (p
*Decoder
) unmarshalAttr(val reflect
.Value
, attr Attr
) error
{
241 if val
.Kind() == reflect
.Ptr
{
243 val
.Set(reflect
.New(val
.Type().Elem()))
247 if val
.CanInterface() && val
.Type().Implements(unmarshalerAttrType
) {
248 // This is an unmarshaler with a non-pointer receiver,
249 // so it's likely to be incorrect, but we do what we're told.
250 return val
.Interface().(UnmarshalerAttr
).UnmarshalXMLAttr(attr
)
254 if pv
.CanInterface() && pv
.Type().Implements(unmarshalerAttrType
) {
255 return pv
.Interface().(UnmarshalerAttr
).UnmarshalXMLAttr(attr
)
259 // Not an UnmarshalerAttr; try encoding.TextUnmarshaler.
260 if val
.CanInterface() && val
.Type().Implements(textUnmarshalerType
) {
261 // This is an unmarshaler with a non-pointer receiver,
262 // so it's likely to be incorrect, but we do what we're told.
263 return val
.Interface().(encoding
.TextUnmarshaler
).UnmarshalText([]byte(attr
.Value
))
267 if pv
.CanInterface() && pv
.Type().Implements(textUnmarshalerType
) {
268 return pv
.Interface().(encoding
.TextUnmarshaler
).UnmarshalText([]byte(attr
.Value
))
272 if val
.Type().Kind() == reflect
.Slice
&& val
.Type().Elem().Kind() != reflect
.Uint8
{
273 // Slice of element values.
276 val
.Set(reflect
.Append(val
, reflect
.Zero(val
.Type().Elem())))
278 // Recur to read element into slice.
279 if err
:= p
.unmarshalAttr(val
.Index(n
), attr
); err
!= nil {
286 if val
.Type() == attrType
{
287 val
.Set(reflect
.ValueOf(attr
))
291 return copyValue(val
, []byte(attr
.Value
))
295 attrType
= reflect
.TypeOf(Attr
{})
296 unmarshalerType
= reflect
.TypeOf((*Unmarshaler
)(nil)).Elem()
297 unmarshalerAttrType
= reflect
.TypeOf((*UnmarshalerAttr
)(nil)).Elem()
298 textUnmarshalerType
= reflect
.TypeOf((*encoding
.TextUnmarshaler
)(nil)).Elem()
301 // Unmarshal a single XML element into val.
302 func (p
*Decoder
) unmarshal(val reflect
.Value
, start
*StartElement
) error
{
303 // Find start element if we need it.
306 tok
, err
:= p
.Token()
310 if t
, ok
:= tok
.(StartElement
); ok
{
317 // Load value from interface, but only if the result will be
318 // usefully addressable.
319 if val
.Kind() == reflect
.Interface
&& !val
.IsNil() {
321 if e
.Kind() == reflect
.Ptr
&& !e
.IsNil() {
326 if val
.Kind() == reflect
.Ptr
{
328 val
.Set(reflect
.New(val
.Type().Elem()))
333 if val
.CanInterface() && val
.Type().Implements(unmarshalerType
) {
334 // This is an unmarshaler with a non-pointer receiver,
335 // so it's likely to be incorrect, but we do what we're told.
336 return p
.unmarshalInterface(val
.Interface().(Unmarshaler
), start
)
341 if pv
.CanInterface() && pv
.Type().Implements(unmarshalerType
) {
342 return p
.unmarshalInterface(pv
.Interface().(Unmarshaler
), start
)
346 if val
.CanInterface() && val
.Type().Implements(textUnmarshalerType
) {
347 return p
.unmarshalTextInterface(val
.Interface().(encoding
.TextUnmarshaler
))
352 if pv
.CanInterface() && pv
.Type().Implements(textUnmarshalerType
) {
353 return p
.unmarshalTextInterface(pv
.Interface().(encoding
.TextUnmarshaler
))
359 saveData reflect
.Value
361 saveComment reflect
.Value
362 saveXML reflect
.Value
365 saveAny reflect
.Value
371 switch v
:= val
; v
.Kind() {
373 return errors
.New("unknown type " + v
.Type().String())
375 case reflect
.Interface
:
376 // TODO: For now, simply ignore the field. In the near
377 // future we may choose to unmarshal the start
378 // element on it, if not nil.
383 if typ
.Elem().Kind() == reflect
.Uint8
{
389 // Slice of element values.
392 v
.Set(reflect
.Append(val
, reflect
.Zero(v
.Type().Elem())))
394 // Recur to read element into slice.
395 if err
:= p
.unmarshal(v
.Index(n
), start
); err
!= nil {
401 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
:
407 v
.Set(reflect
.ValueOf(start
.Name
))
412 tinfo
, err
= getTypeInfo(typ
)
417 // Validate and assign element name.
418 if tinfo
.xmlname
!= nil {
419 finfo
:= tinfo
.xmlname
420 if finfo
.name
!= "" && finfo
.name
!= start
.Name
.Local
{
421 return UnmarshalError("expected element type <" + finfo
.name
+ "> but have <" + start
.Name
.Local
+ ">")
423 if finfo
.xmlns
!= "" && finfo
.xmlns
!= start
.Name
.Space
{
424 e
:= "expected element <" + finfo
.name
+ "> in name space " + finfo
.xmlns
+ " but have "
425 if start
.Name
.Space
== "" {
428 e
+= start
.Name
.Space
430 return UnmarshalError(e
)
432 fv
:= finfo
.value(sv
)
433 if _
, ok
:= fv
.Interface().(Name
); ok
{
434 fv
.Set(reflect
.ValueOf(start
.Name
))
438 // Assign attributes.
439 for _
, a
:= range start
.Attr
{
442 for i
:= range tinfo
.fields
{
443 finfo
:= &tinfo
.fields
[i
]
444 switch finfo
.flags
& fMode
{
446 strv
:= finfo
.value(sv
)
447 if a
.Name
.Local
== finfo
.name
&& (finfo
.xmlns
== "" || finfo
.xmlns
== a
.Name
.Space
) {
448 if err
:= p
.unmarshalAttr(strv
, a
); err
!= nil {
460 if !handled
&& any
>= 0 {
461 finfo
:= &tinfo
.fields
[any
]
462 strv
:= finfo
.value(sv
)
463 if err
:= p
.unmarshalAttr(strv
, a
); err
!= nil {
469 // Determine whether we need to save character data or comments.
470 for i
:= range tinfo
.fields
{
471 finfo
:= &tinfo
.fields
[i
]
472 switch finfo
.flags
& fMode
{
473 case fCDATA
, fCharData
:
474 if !saveData
.IsValid() {
475 saveData
= finfo
.value(sv
)
479 if !saveComment
.IsValid() {
480 saveComment
= finfo
.value(sv
)
483 case fAny
, fAny | fElement
:
484 if !saveAny
.IsValid() {
485 saveAny
= finfo
.value(sv
)
489 if !saveXML
.IsValid() {
490 saveXML
= finfo
.value(sv
)
493 p
.saved
= new(bytes
.Buffer
)
495 saveXMLIndex
= p
.savedOffset()
503 // Process sub-elements along the way.
507 if saveXML
.IsValid() {
508 savedOffset
= p
.savedOffset()
510 tok
, err
:= p
.Token()
514 switch t
:= tok
.(type) {
518 consumed
, err
= p
.unmarshalPath(tinfo
, sv
, nil, &t
)
522 if !consumed
&& saveAny
.IsValid() {
524 if err
:= p
.unmarshal(saveAny
, &t
); err
!= nil {
530 if err
:= p
.Skip(); err
!= nil {
536 if saveXML
.IsValid() {
537 saveXMLData
= p
.saved
.Bytes()[saveXMLIndex
:savedOffset
]
538 if saveXMLIndex
== 0 {
545 if saveData
.IsValid() {
546 data
= append(data
, t
...)
550 if saveComment
.IsValid() {
551 comment
= append(comment
, t
...)
556 if saveData
.IsValid() && saveData
.CanInterface() && saveData
.Type().Implements(textUnmarshalerType
) {
557 if err
:= saveData
.Interface().(encoding
.TextUnmarshaler
).UnmarshalText(data
); err
!= nil {
560 saveData
= reflect
.Value
{}
563 if saveData
.IsValid() && saveData
.CanAddr() {
564 pv
:= saveData
.Addr()
565 if pv
.CanInterface() && pv
.Type().Implements(textUnmarshalerType
) {
566 if err
:= pv
.Interface().(encoding
.TextUnmarshaler
).UnmarshalText(data
); err
!= nil {
569 saveData
= reflect
.Value
{}
573 if err
:= copyValue(saveData
, data
); err
!= nil {
577 switch t
:= saveComment
; t
.Kind() {
579 t
.SetString(string(comment
))
581 t
.Set(reflect
.ValueOf(comment
))
584 switch t
:= saveXML
; t
.Kind() {
586 t
.SetString(string(saveXMLData
))
588 if t
.Type().Elem().Kind() == reflect
.Uint8
{
589 t
.Set(reflect
.ValueOf(saveXMLData
))
596 func copyValue(dst reflect
.Value
, src
[]byte) (err error
) {
599 if dst
.Kind() == reflect
.Ptr
{
601 dst
.Set(reflect
.New(dst
.Type().Elem()))
606 // Save accumulated data.
608 case reflect
.Invalid
:
609 // Probably a comment.
611 return errors
.New("cannot unmarshal into " + dst0
.Type().String())
612 case reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
:
617 itmp
, err
:= strconv
.ParseInt(string(src
), 10, dst
.Type().Bits())
622 case reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
627 utmp
, err
:= strconv
.ParseUint(string(src
), 10, dst
.Type().Bits())
632 case reflect
.Float32
, reflect
.Float64
:
637 ftmp
, err
:= strconv
.ParseFloat(string(src
), dst
.Type().Bits())
647 value
, err
:= strconv
.ParseBool(strings
.TrimSpace(string(src
)))
653 dst
.SetString(string(src
))
656 // non-nil to flag presence
664 // unmarshalPath walks down an XML structure looking for wanted
665 // paths, and calls unmarshal on them.
666 // The consumed result tells whether XML elements have been consumed
667 // from the Decoder until start's matching end element, or if it's
668 // still untouched because start is uninteresting for sv's fields.
669 func (p
*Decoder
) unmarshalPath(tinfo
*typeInfo
, sv reflect
.Value
, parents
[]string, start
*StartElement
) (consumed
bool, err error
) {
672 for i
:= range tinfo
.fields
{
673 finfo
:= &tinfo
.fields
[i
]
674 if finfo
.flags
&fElement
== 0 ||
len(finfo
.parents
) < len(parents
) || finfo
.xmlns
!= "" && finfo
.xmlns
!= start
.Name
.Space
{
677 for j
:= range parents
{
678 if parents
[j
] != finfo
.parents
[j
] {
682 if len(finfo
.parents
) == len(parents
) && finfo
.name
== start
.Name
.Local
{
683 // It's a perfect match, unmarshal the field.
684 return true, p
.unmarshal(finfo
.value(sv
), start
)
686 if len(finfo
.parents
) > len(parents
) && finfo
.parents
[len(parents
)] == start
.Name
.Local
{
687 // It's a prefix for the field. Break and recurse
688 // since it's not ok for one field path to be itself
689 // the prefix for another field path.
692 // We can reuse the same slice as long as we
693 // don't try to append to it.
694 parents
= finfo
.parents
[:len(parents
)+1]
699 // We have no business with this element.
702 // The element is not a perfect match for any field, but one
703 // or more fields have the path to this element as a parent
704 // prefix. Recurse and attempt to match these.
711 switch t
:= tok
.(type) {
713 consumed2
, err
:= p
.unmarshalPath(tinfo
, sv
, parents
, &t
)
718 if err
:= p
.Skip(); err
!= nil {
728 // Skip reads tokens until it has consumed the end element
729 // matching the most recent start element already consumed.
730 // It recurs if it encounters a start element, so it can be used to
731 // skip nested structures.
732 // It returns nil if it finds an end element matching the start
733 // element; otherwise it returns an error describing the problem.
734 func (d
*Decoder
) Skip() error
{
736 tok
, err
:= d
.Token()
742 if err
:= d
.Skip(); err
!= nil {