unmarshal.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package xmlutil
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/xml"
  6. "fmt"
  7. "io"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/aws/aws-sdk-go/aws/awserr"
  13. "github.com/aws/aws-sdk-go/private/protocol"
  14. )
  15. // UnmarshalXMLError unmarshals the XML error from the stream into the value
  16. // type specified. The value must be a pointer. If the message fails to
  17. // unmarshal, the message content will be included in the returned error as a
  18. // awserr.UnmarshalError.
  19. func UnmarshalXMLError(v interface{}, stream io.Reader) error {
  20. var errBuf bytes.Buffer
  21. body := io.TeeReader(stream, &errBuf)
  22. err := xml.NewDecoder(body).Decode(v)
  23. if err != nil && err != io.EOF {
  24. return awserr.NewUnmarshalError(err,
  25. "failed to unmarshal error message", errBuf.Bytes())
  26. }
  27. return nil
  28. }
  29. // UnmarshalXML deserializes an xml.Decoder into the container v. V
  30. // needs to match the shape of the XML expected to be decoded.
  31. // If the shape doesn't match unmarshaling will fail.
  32. func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error {
  33. n, err := XMLToStruct(d, nil)
  34. if err != nil {
  35. return err
  36. }
  37. if n.Children != nil {
  38. for _, root := range n.Children {
  39. for _, c := range root {
  40. if wrappedChild, ok := c.Children[wrapper]; ok {
  41. c = wrappedChild[0] // pull out wrapped element
  42. }
  43. err = parse(reflect.ValueOf(v), c, "")
  44. if err != nil {
  45. if err == io.EOF {
  46. return nil
  47. }
  48. return err
  49. }
  50. }
  51. }
  52. return nil
  53. }
  54. return nil
  55. }
  56. // parse deserializes any value from the XMLNode. The type tag is used to infer the type, or reflect
  57. // will be used to determine the type from r.
  58. func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
  59. xml := tag.Get("xml")
  60. if len(xml) != 0 {
  61. name := strings.SplitAfterN(xml, ",", 2)[0]
  62. if name == "-" {
  63. return nil
  64. }
  65. }
  66. rtype := r.Type()
  67. if rtype.Kind() == reflect.Ptr {
  68. rtype = rtype.Elem() // check kind of actual element type
  69. }
  70. t := tag.Get("type")
  71. if t == "" {
  72. switch rtype.Kind() {
  73. case reflect.Struct:
  74. // also it can't be a time object
  75. if _, ok := r.Interface().(*time.Time); !ok {
  76. t = "structure"
  77. }
  78. case reflect.Slice:
  79. // also it can't be a byte slice
  80. if _, ok := r.Interface().([]byte); !ok {
  81. t = "list"
  82. }
  83. case reflect.Map:
  84. t = "map"
  85. }
  86. }
  87. switch t {
  88. case "structure":
  89. if field, ok := rtype.FieldByName("_"); ok {
  90. tag = field.Tag
  91. }
  92. return parseStruct(r, node, tag)
  93. case "list":
  94. return parseList(r, node, tag)
  95. case "map":
  96. return parseMap(r, node, tag)
  97. default:
  98. return parseScalar(r, node, tag)
  99. }
  100. }
  101. // parseStruct deserializes a structure and its fields from an XMLNode. Any nested
  102. // types in the structure will also be deserialized.
  103. func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
  104. t := r.Type()
  105. if r.Kind() == reflect.Ptr {
  106. if r.IsNil() { // create the structure if it's nil
  107. s := reflect.New(r.Type().Elem())
  108. r.Set(s)
  109. r = s
  110. }
  111. r = r.Elem()
  112. t = t.Elem()
  113. }
  114. // unwrap any payloads
  115. if payload := tag.Get("payload"); payload != "" {
  116. field, _ := t.FieldByName(payload)
  117. return parseStruct(r.FieldByName(payload), node, field.Tag)
  118. }
  119. for i := 0; i < t.NumField(); i++ {
  120. field := t.Field(i)
  121. if c := field.Name[0:1]; strings.ToLower(c) == c {
  122. continue // ignore unexported fields
  123. }
  124. // figure out what this field is called
  125. name := field.Name
  126. if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" {
  127. name = field.Tag.Get("locationNameList")
  128. } else if locName := field.Tag.Get("locationName"); locName != "" {
  129. name = locName
  130. }
  131. // try to find the field by name in elements
  132. elems := node.Children[name]
  133. if elems == nil { // try to find the field in attributes
  134. if val, ok := node.findElem(name); ok {
  135. elems = []*XMLNode{{Text: val}}
  136. }
  137. }
  138. member := r.FieldByName(field.Name)
  139. for _, elem := range elems {
  140. err := parse(member, elem, field.Tag)
  141. if err != nil {
  142. return err
  143. }
  144. }
  145. }
  146. return nil
  147. }
  148. // parseList deserializes a list of values from an XML node. Each list entry
  149. // will also be deserialized.
  150. func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
  151. t := r.Type()
  152. if tag.Get("flattened") == "" { // look at all item entries
  153. mname := "member"
  154. if name := tag.Get("locationNameList"); name != "" {
  155. mname = name
  156. }
  157. if Children, ok := node.Children[mname]; ok {
  158. if r.IsNil() {
  159. r.Set(reflect.MakeSlice(t, len(Children), len(Children)))
  160. }
  161. for i, c := range Children {
  162. err := parse(r.Index(i), c, "")
  163. if err != nil {
  164. return err
  165. }
  166. }
  167. }
  168. } else { // flattened list means this is a single element
  169. if r.IsNil() {
  170. r.Set(reflect.MakeSlice(t, 0, 0))
  171. }
  172. childR := reflect.Zero(t.Elem())
  173. r.Set(reflect.Append(r, childR))
  174. err := parse(r.Index(r.Len()-1), node, "")
  175. if err != nil {
  176. return err
  177. }
  178. }
  179. return nil
  180. }
  181. // parseMap deserializes a map from an XMLNode. The direct children of the XMLNode
  182. // will also be deserialized as map entries.
  183. func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
  184. if r.IsNil() {
  185. r.Set(reflect.MakeMap(r.Type()))
  186. }
  187. if tag.Get("flattened") == "" { // look at all child entries
  188. for _, entry := range node.Children["entry"] {
  189. parseMapEntry(r, entry, tag)
  190. }
  191. } else { // this element is itself an entry
  192. parseMapEntry(r, node, tag)
  193. }
  194. return nil
  195. }
  196. // parseMapEntry deserializes a map entry from a XML node.
  197. func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
  198. kname, vname := "key", "value"
  199. if n := tag.Get("locationNameKey"); n != "" {
  200. kname = n
  201. }
  202. if n := tag.Get("locationNameValue"); n != "" {
  203. vname = n
  204. }
  205. keys, ok := node.Children[kname]
  206. values := node.Children[vname]
  207. if ok {
  208. for i, key := range keys {
  209. keyR := reflect.ValueOf(key.Text)
  210. value := values[i]
  211. valueR := reflect.New(r.Type().Elem()).Elem()
  212. parse(valueR, value, "")
  213. r.SetMapIndex(keyR, valueR)
  214. }
  215. }
  216. return nil
  217. }
  218. // parseScaller deserializes an XMLNode value into a concrete type based on the
  219. // interface type of r.
  220. //
  221. // Error is returned if the deserialization fails due to invalid type conversion,
  222. // or unsupported interface type.
  223. func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
  224. switch r.Interface().(type) {
  225. case *string:
  226. r.Set(reflect.ValueOf(&node.Text))
  227. return nil
  228. case []byte:
  229. b, err := base64.StdEncoding.DecodeString(node.Text)
  230. if err != nil {
  231. return err
  232. }
  233. r.Set(reflect.ValueOf(b))
  234. case *bool:
  235. v, err := strconv.ParseBool(node.Text)
  236. if err != nil {
  237. return err
  238. }
  239. r.Set(reflect.ValueOf(&v))
  240. case *int64:
  241. v, err := strconv.ParseInt(node.Text, 10, 64)
  242. if err != nil {
  243. return err
  244. }
  245. r.Set(reflect.ValueOf(&v))
  246. case *float64:
  247. v, err := strconv.ParseFloat(node.Text, 64)
  248. if err != nil {
  249. return err
  250. }
  251. r.Set(reflect.ValueOf(&v))
  252. case *time.Time:
  253. format := tag.Get("timestampFormat")
  254. if len(format) == 0 {
  255. format = protocol.ISO8601TimeFormatName
  256. }
  257. t, err := protocol.ParseTime(format, node.Text)
  258. if err != nil {
  259. return err
  260. }
  261. r.Set(reflect.ValueOf(&t))
  262. default:
  263. return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type())
  264. }
  265. return nil
  266. }