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