github.com/euank/go@v0.0.0-20160829210321-495514729181/src/encoding/xml/read.go (about) 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 5 package xml 6 7 import ( 8 "bytes" 9 "encoding" 10 "errors" 11 "fmt" 12 "reflect" 13 "strconv" 14 "strings" 15 ) 16 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 20 // of named values. 21 // See package json for a textual representation more suitable 22 // to data structures. 23 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 27 // discarded. 28 // 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 32 // field names. 33 // 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). 37 // 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. 41 // 42 // * If the struct has a field named XMLName of type Name, 43 // Unmarshal records the element name in that field. 44 // 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 48 // returns an error. 49 // 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. 54 // 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. 59 // 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. 64 // 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 ">". 71 // 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. 76 // 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. 80 // 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. 84 // 85 // * An anonymous struct field is handled as if the fields of its 86 // value were part of the outer struct. 87 // 88 // * A struct field with tag "-" is never unmarshalled into. 89 // 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. 93 // 94 // Unmarshal maps an attribute value to a string or []byte by saving 95 // the value in the string or slice. 96 // 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. 99 // 100 // Unmarshal maps an XML element or attribute value to a bool by 101 // setting it to the boolean value represented by the string. 102 // 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 106 // overflow. 107 // 108 // Unmarshal maps an XML element to a Name by recording the element 109 // name. 110 // 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. 113 // 114 func Unmarshal(data []byte, v interface{}) error { 115 return NewDecoder(bytes.NewReader(data)).Decode(v) 116 } 117 118 // Decode works like 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) 122 } 123 124 // DecodeElement works like 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") 132 } 133 return d.unmarshal(val.Elem(), start) 134 } 135 136 // An UnmarshalError represents an error in the unmarshalling process. 137 type UnmarshalError string 138 139 func (e UnmarshalError) Error() string { return string(e) } 140 141 // Unmarshaler is the interface implemented by objects that can unmarshal 142 // an XML element description of themselves. 143 // 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 158 } 159 160 // UnmarshalerAttr is the interface implemented by objects that can unmarshal 161 // an XML attribute description of themselves. 162 // 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 170 } 171 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) 175 if t.Name() != "" { 176 return t.String() 177 } 178 return "(" + t.String() + ")" 179 } 180 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. 185 p.pushEOF() 186 187 p.unmarshalDepth++ 188 err := val.UnmarshalXML(p, *start) 189 p.unmarshalDepth-- 190 if err != nil { 191 p.popEOF() 192 return err 193 } 194 195 if !p.popEOF() { 196 return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local) 197 } 198 199 return nil 200 } 201 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 { 206 var buf []byte 207 depth := 1 208 for depth > 0 { 209 t, err := p.Token() 210 if err != nil { 211 return err 212 } 213 switch t := t.(type) { 214 case CharData: 215 if depth == 1 { 216 buf = append(buf, t...) 217 } 218 case StartElement: 219 depth++ 220 case EndElement: 221 depth-- 222 } 223 } 224 return val.UnmarshalText(buf) 225 } 226 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 { 230 if val.IsNil() { 231 val.Set(reflect.New(val.Type().Elem())) 232 } 233 val = val.Elem() 234 } 235 if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) { 236 // This is an unmarshaler with a non-pointer receiver, 237 // so it's likely to be incorrect, but we do what we're told. 238 return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr) 239 } 240 if val.CanAddr() { 241 pv := val.Addr() 242 if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) { 243 return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr) 244 } 245 } 246 247 // Not an UnmarshalerAttr; try encoding.TextUnmarshaler. 248 if val.CanInterface() && val.Type().Implements(textUnmarshalerType) { 249 // This is an unmarshaler with a non-pointer receiver, 250 // so it's likely to be incorrect, but we do what we're told. 251 return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value)) 252 } 253 if val.CanAddr() { 254 pv := val.Addr() 255 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { 256 return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value)) 257 } 258 } 259 return copyValue(val, []byte(attr.Value)) 260 } 261 262 var ( 263 unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() 264 unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem() 265 textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() 266 ) 267 268 // Unmarshal a single XML element into val. 269 func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error { 270 // Find start element if we need it. 271 if start == nil { 272 for { 273 tok, err := p.Token() 274 if err != nil { 275 return err 276 } 277 if t, ok := tok.(StartElement); ok { 278 start = &t 279 break 280 } 281 } 282 } 283 284 // Load value from interface, but only if the result will be 285 // usefully addressable. 286 if val.Kind() == reflect.Interface && !val.IsNil() { 287 e := val.Elem() 288 if e.Kind() == reflect.Ptr && !e.IsNil() { 289 val = e 290 } 291 } 292 293 if val.Kind() == reflect.Ptr { 294 if val.IsNil() { 295 val.Set(reflect.New(val.Type().Elem())) 296 } 297 val = val.Elem() 298 } 299 300 if val.CanInterface() && val.Type().Implements(unmarshalerType) { 301 // This is an unmarshaler with a non-pointer receiver, 302 // so it's likely to be incorrect, but we do what we're told. 303 return p.unmarshalInterface(val.Interface().(Unmarshaler), start) 304 } 305 306 if val.CanAddr() { 307 pv := val.Addr() 308 if pv.CanInterface() && pv.Type().Implements(unmarshalerType) { 309 return p.unmarshalInterface(pv.Interface().(Unmarshaler), start) 310 } 311 } 312 313 if val.CanInterface() && val.Type().Implements(textUnmarshalerType) { 314 return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler), start) 315 } 316 317 if val.CanAddr() { 318 pv := val.Addr() 319 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { 320 return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler), start) 321 } 322 } 323 324 var ( 325 data []byte 326 saveData reflect.Value 327 comment []byte 328 saveComment reflect.Value 329 saveXML reflect.Value 330 saveXMLIndex int 331 saveXMLData []byte 332 saveAny reflect.Value 333 sv reflect.Value 334 tinfo *typeInfo 335 err error 336 ) 337 338 switch v := val; v.Kind() { 339 default: 340 return errors.New("unknown type " + v.Type().String()) 341 342 case reflect.Interface: 343 // TODO: For now, simply ignore the field. In the near 344 // future we may choose to unmarshal the start 345 // element on it, if not nil. 346 return p.Skip() 347 348 case reflect.Slice: 349 typ := v.Type() 350 if typ.Elem().Kind() == reflect.Uint8 { 351 // []byte 352 saveData = v 353 break 354 } 355 356 // Slice of element values. 357 // Grow slice. 358 n := v.Len() 359 if n >= v.Cap() { 360 ncap := 2 * n 361 if ncap < 4 { 362 ncap = 4 363 } 364 new := reflect.MakeSlice(typ, n, ncap) 365 reflect.Copy(new, v) 366 v.Set(new) 367 } 368 v.SetLen(n + 1) 369 370 // Recur to read element into slice. 371 if err := p.unmarshal(v.Index(n), start); err != nil { 372 v.SetLen(n) 373 return err 374 } 375 return nil 376 377 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: 378 saveData = v 379 380 case reflect.Struct: 381 typ := v.Type() 382 if typ == nameType { 383 v.Set(reflect.ValueOf(start.Name)) 384 break 385 } 386 387 sv = v 388 tinfo, err = getTypeInfo(typ) 389 if err != nil { 390 return err 391 } 392 393 // Validate and assign element name. 394 if tinfo.xmlname != nil { 395 finfo := tinfo.xmlname 396 if finfo.name != "" && finfo.name != start.Name.Local { 397 return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">") 398 } 399 if finfo.xmlns != "" && finfo.xmlns != start.Name.Space { 400 e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have " 401 if start.Name.Space == "" { 402 e += "no name space" 403 } else { 404 e += start.Name.Space 405 } 406 return UnmarshalError(e) 407 } 408 fv := finfo.value(sv) 409 if _, ok := fv.Interface().(Name); ok { 410 fv.Set(reflect.ValueOf(start.Name)) 411 } 412 } 413 414 // Assign attributes. 415 // Also, determine whether we need to save character data or comments. 416 for i := range tinfo.fields { 417 finfo := &tinfo.fields[i] 418 switch finfo.flags & fMode { 419 case fAttr: 420 strv := finfo.value(sv) 421 // Look for attribute. 422 for _, a := range start.Attr { 423 if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) { 424 if err := p.unmarshalAttr(strv, a); err != nil { 425 return err 426 } 427 break 428 } 429 } 430 431 case fCDATA, fCharData: 432 if !saveData.IsValid() { 433 saveData = finfo.value(sv) 434 } 435 436 case fComment: 437 if !saveComment.IsValid() { 438 saveComment = finfo.value(sv) 439 } 440 441 case fAny, fAny | fElement: 442 if !saveAny.IsValid() { 443 saveAny = finfo.value(sv) 444 } 445 446 case fInnerXml: 447 if !saveXML.IsValid() { 448 saveXML = finfo.value(sv) 449 if p.saved == nil { 450 saveXMLIndex = 0 451 p.saved = new(bytes.Buffer) 452 } else { 453 saveXMLIndex = p.savedOffset() 454 } 455 } 456 } 457 } 458 } 459 460 // Find end element. 461 // Process sub-elements along the way. 462 Loop: 463 for { 464 var savedOffset int 465 if saveXML.IsValid() { 466 savedOffset = p.savedOffset() 467 } 468 tok, err := p.Token() 469 if err != nil { 470 return err 471 } 472 switch t := tok.(type) { 473 case StartElement: 474 consumed := false 475 if sv.IsValid() { 476 consumed, err = p.unmarshalPath(tinfo, sv, nil, &t) 477 if err != nil { 478 return err 479 } 480 if !consumed && saveAny.IsValid() { 481 consumed = true 482 if err := p.unmarshal(saveAny, &t); err != nil { 483 return err 484 } 485 } 486 } 487 if !consumed { 488 if err := p.Skip(); err != nil { 489 return err 490 } 491 } 492 493 case EndElement: 494 if saveXML.IsValid() { 495 saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset] 496 if saveXMLIndex == 0 { 497 p.saved = nil 498 } 499 } 500 break Loop 501 502 case CharData: 503 if saveData.IsValid() { 504 data = append(data, t...) 505 } 506 507 case Comment: 508 if saveComment.IsValid() { 509 comment = append(comment, t...) 510 } 511 } 512 } 513 514 if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) { 515 if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { 516 return err 517 } 518 saveData = reflect.Value{} 519 } 520 521 if saveData.IsValid() && saveData.CanAddr() { 522 pv := saveData.Addr() 523 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { 524 if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { 525 return err 526 } 527 saveData = reflect.Value{} 528 } 529 } 530 531 if err := copyValue(saveData, data); err != nil { 532 return err 533 } 534 535 switch t := saveComment; t.Kind() { 536 case reflect.String: 537 t.SetString(string(comment)) 538 case reflect.Slice: 539 t.Set(reflect.ValueOf(comment)) 540 } 541 542 switch t := saveXML; t.Kind() { 543 case reflect.String: 544 t.SetString(string(saveXMLData)) 545 case reflect.Slice: 546 t.Set(reflect.ValueOf(saveXMLData)) 547 } 548 549 return nil 550 } 551 552 func copyValue(dst reflect.Value, src []byte) (err error) { 553 dst0 := dst 554 555 if dst.Kind() == reflect.Ptr { 556 if dst.IsNil() { 557 dst.Set(reflect.New(dst.Type().Elem())) 558 } 559 dst = dst.Elem() 560 } 561 562 // Save accumulated data. 563 switch dst.Kind() { 564 case reflect.Invalid: 565 // Probably a comment. 566 default: 567 return errors.New("cannot unmarshal into " + dst0.Type().String()) 568 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 569 itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits()) 570 if err != nil { 571 return err 572 } 573 dst.SetInt(itmp) 574 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 575 utmp, err := strconv.ParseUint(string(src), 10, dst.Type().Bits()) 576 if err != nil { 577 return err 578 } 579 dst.SetUint(utmp) 580 case reflect.Float32, reflect.Float64: 581 ftmp, err := strconv.ParseFloat(string(src), dst.Type().Bits()) 582 if err != nil { 583 return err 584 } 585 dst.SetFloat(ftmp) 586 case reflect.Bool: 587 value, err := strconv.ParseBool(strings.TrimSpace(string(src))) 588 if err != nil { 589 return err 590 } 591 dst.SetBool(value) 592 case reflect.String: 593 dst.SetString(string(src)) 594 case reflect.Slice: 595 if len(src) == 0 { 596 // non-nil to flag presence 597 src = []byte{} 598 } 599 dst.SetBytes(src) 600 } 601 return nil 602 } 603 604 // unmarshalPath walks down an XML structure looking for wanted 605 // paths, and calls unmarshal on them. 606 // The consumed result tells whether XML elements have been consumed 607 // from the Decoder until start's matching end element, or if it's 608 // still untouched because start is uninteresting for sv's fields. 609 func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) { 610 recurse := false 611 Loop: 612 for i := range tinfo.fields { 613 finfo := &tinfo.fields[i] 614 if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space { 615 continue 616 } 617 for j := range parents { 618 if parents[j] != finfo.parents[j] { 619 continue Loop 620 } 621 } 622 if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local { 623 // It's a perfect match, unmarshal the field. 624 return true, p.unmarshal(finfo.value(sv), start) 625 } 626 if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local { 627 // It's a prefix for the field. Break and recurse 628 // since it's not ok for one field path to be itself 629 // the prefix for another field path. 630 recurse = true 631 632 // We can reuse the same slice as long as we 633 // don't try to append to it. 634 parents = finfo.parents[:len(parents)+1] 635 break 636 } 637 } 638 if !recurse { 639 // We have no business with this element. 640 return false, nil 641 } 642 // The element is not a perfect match for any field, but one 643 // or more fields have the path to this element as a parent 644 // prefix. Recurse and attempt to match these. 645 for { 646 var tok Token 647 tok, err = p.Token() 648 if err != nil { 649 return true, err 650 } 651 switch t := tok.(type) { 652 case StartElement: 653 consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t) 654 if err != nil { 655 return true, err 656 } 657 if !consumed2 { 658 if err := p.Skip(); err != nil { 659 return true, err 660 } 661 } 662 case EndElement: 663 return true, nil 664 } 665 } 666 } 667 668 // Skip reads tokens until it has consumed the end element 669 // matching the most recent start element already consumed. 670 // It recurs if it encounters a start element, so it can be used to 671 // skip nested structures. 672 // It returns nil if it finds an end element matching the start 673 // element; otherwise it returns an error describing the problem. 674 func (d *Decoder) Skip() error { 675 for { 676 tok, err := d.Token() 677 if err != nil { 678 return err 679 } 680 switch tok.(type) { 681 case StartElement: 682 if err := d.Skip(); err != nil { 683 return err 684 } 685 case EndElement: 686 return nil 687 } 688 } 689 }