read.go 22 KB

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