Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

693 rader
20 KiB

  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. // Unmarshal a single XML element into val.
  250. func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error {
  251. // Find start element if we need it.
  252. if start == nil {
  253. for {
  254. tok, err := p.Token()
  255. if err != nil {
  256. return err
  257. }
  258. if t, ok := tok.(StartElement); ok {
  259. start = &t
  260. break
  261. }
  262. }
  263. }
  264. // Load value from interface, but only if the result will be
  265. // usefully addressable.
  266. if val.Kind() == reflect.Interface && !val.IsNil() {
  267. e := val.Elem()
  268. if e.Kind() == reflect.Ptr && !e.IsNil() {
  269. val = e
  270. }
  271. }
  272. if val.Kind() == reflect.Ptr {
  273. if val.IsNil() {
  274. val.Set(reflect.New(val.Type().Elem()))
  275. }
  276. val = val.Elem()
  277. }
  278. if val.CanInterface() && val.Type().Implements(unmarshalerType) {
  279. // This is an unmarshaler with a non-pointer receiver,
  280. // so it's likely to be incorrect, but we do what we're told.
  281. return p.unmarshalInterface(val.Interface().(Unmarshaler), start)
  282. }
  283. if val.CanAddr() {
  284. pv := val.Addr()
  285. if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
  286. return p.unmarshalInterface(pv.Interface().(Unmarshaler), start)
  287. }
  288. }
  289. if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
  290. return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler), start)
  291. }
  292. if val.CanAddr() {
  293. pv := val.Addr()
  294. if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
  295. return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler), start)
  296. }
  297. }
  298. var (
  299. data []byte
  300. saveData reflect.Value
  301. comment []byte
  302. saveComment reflect.Value
  303. saveXML reflect.Value
  304. saveXMLIndex int
  305. saveXMLData []byte
  306. saveAny reflect.Value
  307. sv reflect.Value
  308. tinfo *typeInfo
  309. err error
  310. )
  311. switch v := val; v.Kind() {
  312. default:
  313. return errors.New("unknown type " + v.Type().String())
  314. case reflect.Interface:
  315. // TODO: For now, simply ignore the field. In the near
  316. // future we may choose to unmarshal the start
  317. // element on it, if not nil.
  318. return p.Skip()
  319. case reflect.Slice:
  320. typ := v.Type()
  321. if typ.Elem().Kind() == reflect.Uint8 {
  322. // []byte
  323. saveData = v
  324. break
  325. }
  326. // Slice of element values.
  327. // Grow slice.
  328. n := v.Len()
  329. if n >= v.Cap() {
  330. ncap := 2 * n
  331. if ncap < 4 {
  332. ncap = 4
  333. }
  334. new := reflect.MakeSlice(typ, n, ncap)
  335. reflect.Copy(new, v)
  336. v.Set(new)
  337. }
  338. v.SetLen(n + 1)
  339. // Recur to read element into slice.
  340. if err := p.unmarshal(v.Index(n), start); err != nil {
  341. v.SetLen(n)
  342. return err
  343. }
  344. return nil
  345. 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:
  346. saveData = v
  347. case reflect.Struct:
  348. typ := v.Type()
  349. if typ == nameType {
  350. v.Set(reflect.ValueOf(start.Name))
  351. break
  352. }
  353. sv = v
  354. tinfo, err = getTypeInfo(typ)
  355. if err != nil {
  356. return err
  357. }
  358. // Validate and assign element name.
  359. if tinfo.xmlname != nil {
  360. finfo := tinfo.xmlname
  361. if finfo.name != "" && finfo.name != start.Name.Local {
  362. return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
  363. }
  364. if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
  365. e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
  366. if start.Name.Space == "" {
  367. e += "no name space"
  368. } else {
  369. e += start.Name.Space
  370. }
  371. return UnmarshalError(e)
  372. }
  373. fv := finfo.value(sv)
  374. if _, ok := fv.Interface().(Name); ok {
  375. fv.Set(reflect.ValueOf(start.Name))
  376. }
  377. }
  378. // Assign attributes.
  379. // Also, determine whether we need to save character data or comments.
  380. for i := range tinfo.fields {
  381. finfo := &tinfo.fields[i]
  382. switch finfo.flags & fMode {
  383. case fAttr:
  384. strv := finfo.value(sv)
  385. // Look for attribute.
  386. for _, a := range start.Attr {
  387. if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
  388. if err := p.unmarshalAttr(strv, a); err != nil {
  389. return err
  390. }
  391. break
  392. }
  393. }
  394. case fCharData:
  395. if !saveData.IsValid() {
  396. saveData = finfo.value(sv)
  397. }
  398. case fComment:
  399. if !saveComment.IsValid() {
  400. saveComment = finfo.value(sv)
  401. }
  402. case fAny, fAny | fElement:
  403. if !saveAny.IsValid() {
  404. saveAny = finfo.value(sv)
  405. }
  406. case fInnerXml:
  407. if !saveXML.IsValid() {
  408. saveXML = finfo.value(sv)
  409. if p.saved == nil {
  410. saveXMLIndex = 0
  411. p.saved = new(bytes.Buffer)
  412. } else {
  413. saveXMLIndex = p.savedOffset()
  414. }
  415. }
  416. }
  417. }
  418. }
  419. // Find end element.
  420. // Process sub-elements along the way.
  421. Loop:
  422. for {
  423. var savedOffset int
  424. if saveXML.IsValid() {
  425. savedOffset = p.savedOffset()
  426. }
  427. tok, err := p.Token()
  428. if err != nil {
  429. return err
  430. }
  431. switch t := tok.(type) {
  432. case StartElement:
  433. consumed := false
  434. if sv.IsValid() {
  435. consumed, err = p.unmarshalPath(tinfo, sv, nil, &t)
  436. if err != nil {
  437. return err
  438. }
  439. if !consumed && saveAny.IsValid() {
  440. consumed = true
  441. if err := p.unmarshal(saveAny, &t); err != nil {
  442. return err
  443. }
  444. }
  445. }
  446. if !consumed {
  447. if err := p.Skip(); err != nil {
  448. return err
  449. }
  450. }
  451. case EndElement:
  452. if saveXML.IsValid() {
  453. saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset]
  454. if saveXMLIndex == 0 {
  455. p.saved = nil
  456. }
  457. }
  458. break Loop
  459. case CharData:
  460. if saveData.IsValid() {
  461. data = append(data, t...)
  462. }
  463. case Comment:
  464. if saveComment.IsValid() {
  465. comment = append(comment, t...)
  466. }
  467. }
  468. }
  469. if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
  470. if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
  471. return err
  472. }
  473. saveData = reflect.Value{}
  474. }
  475. if saveData.IsValid() && saveData.CanAddr() {
  476. pv := saveData.Addr()
  477. if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
  478. if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
  479. return err
  480. }
  481. saveData = reflect.Value{}
  482. }
  483. }
  484. if err := copyValue(saveData, data); err != nil {
  485. return err
  486. }
  487. switch t := saveComment; t.Kind() {
  488. case reflect.String:
  489. t.SetString(string(comment))
  490. case reflect.Slice:
  491. t.Set(reflect.ValueOf(comment))
  492. }
  493. switch t := saveXML; t.Kind() {
  494. case reflect.String:
  495. t.SetString(string(saveXMLData))
  496. case reflect.Slice:
  497. t.Set(reflect.ValueOf(saveXMLData))
  498. }
  499. return nil
  500. }
  501. func copyValue(dst reflect.Value, src []byte) (err error) {
  502. dst0 := dst
  503. if dst.Kind() == reflect.Ptr {
  504. if dst.IsNil() {
  505. dst.Set(reflect.New(dst.Type().Elem()))
  506. }
  507. dst = dst.Elem()
  508. }
  509. // Save accumulated data.
  510. switch dst.Kind() {
  511. case reflect.Invalid:
  512. // Probably a comment.
  513. default:
  514. return errors.New("cannot unmarshal into " + dst0.Type().String())
  515. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  516. itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits())
  517. if err != nil {
  518. return err
  519. }
  520. dst.SetInt(itmp)
  521. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  522. utmp, err := strconv.ParseUint(string(src), 10, dst.Type().Bits())
  523. if err != nil {
  524. return err
  525. }
  526. dst.SetUint(utmp)
  527. case reflect.Float32, reflect.Float64:
  528. ftmp, err := strconv.ParseFloat(string(src), dst.Type().Bits())
  529. if err != nil {
  530. return err
  531. }
  532. dst.SetFloat(ftmp)
  533. case reflect.Bool:
  534. value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
  535. if err != nil {
  536. return err
  537. }
  538. dst.SetBool(value)
  539. case reflect.String:
  540. dst.SetString(string(src))
  541. case reflect.Slice:
  542. if len(src) == 0 {
  543. // non-nil to flag presence
  544. src = []byte{}
  545. }
  546. dst.SetBytes(src)
  547. }
  548. return nil
  549. }
  550. // unmarshalPath walks down an XML structure looking for wanted
  551. // paths, and calls unmarshal on them.
  552. // The consumed result tells whether XML elements have been consumed
  553. // from the Decoder until start's matching end element, or if it's
  554. // still untouched because start is uninteresting for sv's fields.
  555. func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) {
  556. recurse := false
  557. Loop:
  558. for i := range tinfo.fields {
  559. finfo := &tinfo.fields[i]
  560. if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
  561. continue
  562. }
  563. for j := range parents {
  564. if parents[j] != finfo.parents[j] {
  565. continue Loop
  566. }
  567. }
  568. if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
  569. // It's a perfect match, unmarshal the field.
  570. return true, p.unmarshal(finfo.value(sv), start)
  571. }
  572. if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
  573. // It's a prefix for the field. Break and recurse
  574. // since it's not ok for one field path to be itself
  575. // the prefix for another field path.
  576. recurse = true
  577. // We can reuse the same slice as long as we
  578. // don't try to append to it.
  579. parents = finfo.parents[:len(parents)+1]
  580. break
  581. }
  582. }
  583. if !recurse {
  584. // We have no business with this element.
  585. return false, nil
  586. }
  587. // The element is not a perfect match for any field, but one
  588. // or more fields have the path to this element as a parent
  589. // prefix. Recurse and attempt to match these.
  590. for {
  591. var tok Token
  592. tok, err = p.Token()
  593. if err != nil {
  594. return true, err
  595. }
  596. switch t := tok.(type) {
  597. case StartElement:
  598. consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t)
  599. if err != nil {
  600. return true, err
  601. }
  602. if !consumed2 {
  603. if err := p.Skip(); err != nil {
  604. return true, err
  605. }
  606. }
  607. case EndElement:
  608. return true, nil
  609. }
  610. }
  611. }
  612. // Skip reads tokens until it has consumed the end element
  613. // matching the most recent start element already consumed.
  614. // It recurs if it encounters a start element, so it can be used to
  615. // skip nested structures.
  616. // It returns nil if it finds an end element matching the start
  617. // element; otherwise it returns an error describing the problem.
  618. func (d *Decoder) Skip() error {
  619. for {
  620. tok, err := d.Token()
  621. if err != nil {
  622. return err
  623. }
  624. switch tok.(type) {
  625. case StartElement:
  626. if err := d.Skip(); err != nil {
  627. return err
  628. }
  629. case EndElement:
  630. return nil
  631. }
  632. }
  633. }