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 xml.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 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.
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.
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 ">".
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.
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.
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.
85 // * An anonymous struct field is handled as if the fields of its
86 // value were part of the outer struct.
88 // * A struct field with tag "-" is never unmarshalled into.
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.
94 // Unmarshal maps an attribute value to a string or []byte by saving
95 // the value in the string or slice.
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.
100 // Unmarshal maps an XML element or attribute value to a bool by
101 // setting it to the boolean value represented by the string.
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
108 // Unmarshal maps an XML element to an xml.Name by recording the
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.
114 func Unmarshal(data
[]byte, v
interface{}) error
{
115 return NewDecoder(bytes
.NewReader(data
)).Decode(v
)
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)
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")
133 return d
.unmarshal(val
.Elem(), start
)
136 // An UnmarshalError represents an error in the unmarshalling process.
137 type UnmarshalError
string
139 func (e UnmarshalError
) Error() string { return string(e
) }
141 // Unmarshaler is the interface implemented by objects that can unmarshal
142 // an XML element description of themselves.
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
160 // UnmarshalerAttr is the interface implemented by objects that can unmarshal
161 // an XML attribute description of themselves.
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
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
)
178 return "(" + t
.String() + ")"
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.
188 err
:= val
.UnmarshalXML(p
, *start
)
196 return fmt
.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val
), start
.Name
.Local
)
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
{
213 switch t
:= t
.(type) {
216 buf
= append(buf
, t
...)
224 return val
.UnmarshalText(buf
)
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
{
231 val
.Set(reflect
.New(val
.Type().Elem()))
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
)
243 if pv
.CanInterface() && pv
.Type().Implements(unmarshalerAttrType
) {
244 return pv
.Interface().(UnmarshalerAttr
).UnmarshalXMLAttr(attr
)
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
))
256 if pv
.CanInterface() && pv
.Type().Implements(textUnmarshalerType
) {
257 return pv
.Interface().(encoding
.TextUnmarshaler
).UnmarshalText([]byte(attr
.Value
))
261 copyValue(val
, []byte(attr
.Value
))
266 unmarshalerType
= reflect
.TypeOf((*Unmarshaler
)(nil)).Elem()
267 unmarshalerAttrType
= reflect
.TypeOf((*UnmarshalerAttr
)(nil)).Elem()
268 textUnmarshalerType
= reflect
.TypeOf((*encoding
.TextUnmarshaler
)(nil)).Elem()
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.
276 tok
, err
:= p
.Token()
280 if t
, ok
:= tok
.(StartElement
); ok
{
287 // Load value from interface, but only if the result will be
288 // usefully addressable.
289 if val
.Kind() == reflect
.Interface
&& !val
.IsNil() {
291 if e
.Kind() == reflect
.Ptr
&& !e
.IsNil() {
296 if val
.Kind() == reflect
.Ptr
{
298 val
.Set(reflect
.New(val
.Type().Elem()))
303 if val
.CanInterface() && val
.Type().Implements(unmarshalerType
) {
304 // This is an unmarshaler with a non-pointer receiver,
305 // so it's likely to be incorrect, but we do what we're told.
306 return p
.unmarshalInterface(val
.Interface().(Unmarshaler
), start
)
311 if pv
.CanInterface() && pv
.Type().Implements(unmarshalerType
) {
312 return p
.unmarshalInterface(pv
.Interface().(Unmarshaler
), start
)
316 if val
.CanInterface() && val
.Type().Implements(textUnmarshalerType
) {
317 return p
.unmarshalTextInterface(val
.Interface().(encoding
.TextUnmarshaler
), start
)
322 if pv
.CanInterface() && pv
.Type().Implements(textUnmarshalerType
) {
323 return p
.unmarshalTextInterface(pv
.Interface().(encoding
.TextUnmarshaler
), start
)
329 saveData reflect
.Value
331 saveComment reflect
.Value
332 saveXML reflect
.Value
335 saveAny reflect
.Value
341 switch v
:= val
; v
.Kind() {
343 return errors
.New("unknown type " + v
.Type().String())
345 case reflect
.Interface
:
346 // TODO: For now, simply ignore the field. In the near
347 // future we may choose to unmarshal the start
348 // element on it, if not nil.
353 if typ
.Elem().Kind() == reflect
.Uint8
{
359 // Slice of element values.
367 new := reflect
.MakeSlice(typ
, n
, ncap
)
373 // Recur to read element into slice.
374 if err
:= p
.unmarshal(v
.Index(n
), start
); err
!= nil {
380 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
:
386 v
.Set(reflect
.ValueOf(start
.Name
))
391 tinfo
, err
= getTypeInfo(typ
)
396 // Validate and assign element name.
397 if tinfo
.xmlname
!= nil {
398 finfo
:= tinfo
.xmlname
399 if finfo
.name
!= "" && finfo
.name
!= start
.Name
.Local
{
400 return UnmarshalError("expected element type <" + finfo
.name
+ "> but have <" + start
.Name
.Local
+ ">")
402 if finfo
.xmlns
!= "" && finfo
.xmlns
!= start
.Name
.Space
{
403 e
:= "expected element <" + finfo
.name
+ "> in name space " + finfo
.xmlns
+ " but have "
404 if start
.Name
.Space
== "" {
407 e
+= start
.Name
.Space
409 return UnmarshalError(e
)
411 fv
:= finfo
.value(sv
)
412 if _
, ok
:= fv
.Interface().(Name
); ok
{
413 fv
.Set(reflect
.ValueOf(start
.Name
))
417 // Assign attributes.
418 // Also, determine whether we need to save character data or comments.
419 for i
:= range tinfo
.fields
{
420 finfo
:= &tinfo
.fields
[i
]
421 switch finfo
.flags
& fMode
{
423 strv
:= finfo
.value(sv
)
424 // Look for attribute.
425 for _
, a
:= range start
.Attr
{
426 if a
.Name
.Local
== finfo
.name
&& (finfo
.xmlns
== "" || finfo
.xmlns
== a
.Name
.Space
) {
427 if err
:= p
.unmarshalAttr(strv
, a
); err
!= nil {
435 if !saveData
.IsValid() {
436 saveData
= finfo
.value(sv
)
440 if !saveComment
.IsValid() {
441 saveComment
= finfo
.value(sv
)
444 case fAny
, fAny | fElement
:
445 if !saveAny
.IsValid() {
446 saveAny
= finfo
.value(sv
)
450 if !saveXML
.IsValid() {
451 saveXML
= finfo
.value(sv
)
454 p
.saved
= new(bytes
.Buffer
)
456 saveXMLIndex
= p
.savedOffset()
464 // Process sub-elements along the way.
468 if saveXML
.IsValid() {
469 savedOffset
= p
.savedOffset()
471 tok
, err
:= p
.Token()
475 switch t
:= tok
.(type) {
479 consumed
, err
= p
.unmarshalPath(tinfo
, sv
, nil, &t
)
483 if !consumed
&& saveAny
.IsValid() {
485 if err
:= p
.unmarshal(saveAny
, &t
); err
!= nil {
491 if err
:= p
.Skip(); err
!= nil {
497 if saveXML
.IsValid() {
498 saveXMLData
= p
.saved
.Bytes()[saveXMLIndex
:savedOffset
]
499 if saveXMLIndex
== 0 {
506 if saveData
.IsValid() {
507 data
= append(data
, t
...)
511 if saveComment
.IsValid() {
512 comment
= append(comment
, t
...)
517 if saveData
.IsValid() && saveData
.CanInterface() && saveData
.Type().Implements(textUnmarshalerType
) {
518 if err
:= saveData
.Interface().(encoding
.TextUnmarshaler
).UnmarshalText(data
); err
!= nil {
521 saveData
= reflect
.Value
{}
524 if saveData
.IsValid() && saveData
.CanAddr() {
525 pv
:= saveData
.Addr()
526 if pv
.CanInterface() && pv
.Type().Implements(textUnmarshalerType
) {
527 if err
:= pv
.Interface().(encoding
.TextUnmarshaler
).UnmarshalText(data
); err
!= nil {
530 saveData
= reflect
.Value
{}
534 if err
:= copyValue(saveData
, data
); err
!= nil {
538 switch t
:= saveComment
; t
.Kind() {
540 t
.SetString(string(comment
))
542 t
.Set(reflect
.ValueOf(comment
))
545 switch t
:= saveXML
; t
.Kind() {
547 t
.SetString(string(saveXMLData
))
549 t
.Set(reflect
.ValueOf(saveXMLData
))
555 func copyValue(dst reflect
.Value
, src
[]byte) (err error
) {
558 if dst
.Kind() == reflect
.Ptr
{
560 dst
.Set(reflect
.New(dst
.Type().Elem()))
565 // Save accumulated data.
567 case reflect
.Invalid
:
568 // Probably a comment.
570 return errors
.New("cannot unmarshal into " + dst0
.Type().String())
571 case reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
:
572 itmp
, err
:= strconv
.ParseInt(string(src
), 10, dst
.Type().Bits())
577 case reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
578 utmp
, err
:= strconv
.ParseUint(string(src
), 10, dst
.Type().Bits())
583 case reflect
.Float32
, reflect
.Float64
:
584 ftmp
, err
:= strconv
.ParseFloat(string(src
), dst
.Type().Bits())
590 value
, err
:= strconv
.ParseBool(strings
.TrimSpace(string(src
)))
596 dst
.SetString(string(src
))
599 // non-nil to flag presence
607 // unmarshalPath walks down an XML structure looking for wanted
608 // paths, and calls unmarshal on them.
609 // The consumed result tells whether XML elements have been consumed
610 // from the Decoder until start's matching end element, or if it's
611 // still untouched because start is uninteresting for sv's fields.
612 func (p
*Decoder
) unmarshalPath(tinfo
*typeInfo
, sv reflect
.Value
, parents
[]string, start
*StartElement
) (consumed
bool, err error
) {
615 for i
:= range tinfo
.fields
{
616 finfo
:= &tinfo
.fields
[i
]
617 if finfo
.flags
&fElement
== 0 ||
len(finfo
.parents
) < len(parents
) || finfo
.xmlns
!= "" && finfo
.xmlns
!= start
.Name
.Space
{
620 for j
:= range parents
{
621 if parents
[j
] != finfo
.parents
[j
] {
625 if len(finfo
.parents
) == len(parents
) && finfo
.name
== start
.Name
.Local
{
626 // It's a perfect match, unmarshal the field.
627 return true, p
.unmarshal(finfo
.value(sv
), start
)
629 if len(finfo
.parents
) > len(parents
) && finfo
.parents
[len(parents
)] == start
.Name
.Local
{
630 // It's a prefix for the field. Break and recurse
631 // since it's not ok for one field path to be itself
632 // the prefix for another field path.
635 // We can reuse the same slice as long as we
636 // don't try to append to it.
637 parents
= finfo
.parents
[:len(parents
)+1]
642 // We have no business with this element.
645 // The element is not a perfect match for any field, but one
646 // or more fields have the path to this element as a parent
647 // prefix. Recurse and attempt to match these.
654 switch t
:= tok
.(type) {
656 consumed2
, err
:= p
.unmarshalPath(tinfo
, sv
, parents
, &t
)
661 if err
:= p
.Skip(); err
!= nil {
671 // Skip reads tokens until it has consumed the end element
672 // matching the most recent start element already consumed.
673 // It recurs if it encounters a start element, so it can be used to
674 // skip nested structures.
675 // It returns nil if it finds an end element matching the start
676 // element; otherwise it returns an error describing the problem.
677 func (d
*Decoder
) Skip() error
{
679 tok
, err
:= d
.Token()
685 if err
:= d
.Skip(); err
!= nil {