github.com/freddyisaac/sicortex-golang@v0.0.0-20231019035217-e03519e66f60/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 unmarshaled 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 unmarshaling 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 copyValue(val, []byte(attr.Value)) 289 return nil 290 } 291 292 var ( 293 attrType = reflect.TypeOf(Attr{}) 294 unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() 295 unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem() 296 textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() 297 ) 298 299 // Unmarshal a single XML element into val. 300 func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error { 301 // Find start element if we need it. 302 if start == nil { 303 for { 304 tok, err := p.Token() 305 if err != nil { 306 return err 307 } 308 if t, ok := tok.(StartElement); ok { 309 start = &t 310 break 311 } 312 } 313 } 314 315 // Load value from interface, but only if the result will be 316 // usefully addressable. 317 if val.Kind() == reflect.Interface && !val.IsNil() { 318 e := val.Elem() 319 if e.Kind() == reflect.Ptr && !e.IsNil() { 320 val = e 321 } 322 } 323 324 if val.Kind() == reflect.Ptr { 325 if val.IsNil() { 326 val.Set(reflect.New(val.Type().Elem())) 327 } 328 val = val.Elem() 329 } 330 331 if val.CanInterface() && val.Type().Implements(unmarshalerType) { 332 // This is an unmarshaler with a non-pointer receiver, 333 // so it's likely to be incorrect, but we do what we're told. 334 return p.unmarshalInterface(val.Interface().(Unmarshaler), start) 335 } 336 337 if val.CanAddr() { 338 pv := val.Addr() 339 if pv.CanInterface() && pv.Type().Implements(unmarshalerType) { 340 return p.unmarshalInterface(pv.Interface().(Unmarshaler), start) 341 } 342 } 343 344 if val.CanInterface() && val.Type().Implements(textUnmarshalerType) { 345 return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler), start) 346 } 347 348 if val.CanAddr() { 349 pv := val.Addr() 350 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { 351 return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler), start) 352 } 353 } 354 355 var ( 356 data []byte 357 saveData reflect.Value 358 comment []byte 359 saveComment reflect.Value 360 saveXML reflect.Value 361 saveXMLIndex int 362 saveXMLData []byte 363 saveAny reflect.Value 364 sv reflect.Value 365 tinfo *typeInfo 366 err error 367 ) 368 369 switch v := val; v.Kind() { 370 default: 371 return errors.New("unknown type " + v.Type().String()) 372 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 379 case reflect.Slice: 380 typ := v.Type() 381 if typ.Elem().Kind() == reflect.Uint8 { 382 // []byte 383 saveData = v 384 break 385 } 386 387 // Slice of element values. 388 // Grow slice. 389 n := v.Len() 390 v.Set(reflect.Append(val, reflect.Zero(v.Type().Elem()))) 391 392 // Recur to read element into slice. 393 if err := p.unmarshal(v.Index(n), start); err != nil { 394 v.SetLen(n) 395 return err 396 } 397 return nil 398 399 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: 400 saveData = v 401 402 case reflect.Struct: 403 typ := v.Type() 404 if typ == nameType { 405 v.Set(reflect.ValueOf(start.Name)) 406 break 407 } 408 409 sv = v 410 tinfo, err = getTypeInfo(typ) 411 if err != nil { 412 return err 413 } 414 415 // Validate and assign element name. 416 if tinfo.xmlname != nil { 417 finfo := tinfo.xmlname 418 if finfo.name != "" && finfo.name != start.Name.Local { 419 return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">") 420 } 421 if finfo.xmlns != "" && finfo.xmlns != start.Name.Space { 422 e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have " 423 if start.Name.Space == "" { 424 e += "no name space" 425 } else { 426 e += start.Name.Space 427 } 428 return UnmarshalError(e) 429 } 430 fv := finfo.value(sv) 431 if _, ok := fv.Interface().(Name); ok { 432 fv.Set(reflect.ValueOf(start.Name)) 433 } 434 } 435 436 // Assign attributes. 437 for _, a := range start.Attr { 438 handled := false 439 any := -1 440 for i := range tinfo.fields { 441 finfo := &tinfo.fields[i] 442 switch finfo.flags & fMode { 443 case fAttr: 444 strv := finfo.value(sv) 445 if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) { 446 if err := p.unmarshalAttr(strv, a); err != nil { 447 return err 448 } 449 handled = true 450 } 451 452 case fAny | fAttr: 453 if any == -1 { 454 any = i 455 } 456 } 457 } 458 if !handled && any >= 0 { 459 finfo := &tinfo.fields[any] 460 strv := finfo.value(sv) 461 if err := p.unmarshalAttr(strv, a); err != nil { 462 return err 463 } 464 } 465 } 466 467 // Determine whether we need to save character data or comments. 468 for i := range tinfo.fields { 469 finfo := &tinfo.fields[i] 470 switch finfo.flags & fMode { 471 case fCDATA, fCharData: 472 if !saveData.IsValid() { 473 saveData = finfo.value(sv) 474 } 475 476 case fComment: 477 if !saveComment.IsValid() { 478 saveComment = finfo.value(sv) 479 } 480 481 case fAny, fAny | fElement: 482 if !saveAny.IsValid() { 483 saveAny = finfo.value(sv) 484 } 485 486 case fInnerXml: 487 if !saveXML.IsValid() { 488 saveXML = finfo.value(sv) 489 if p.saved == nil { 490 saveXMLIndex = 0 491 p.saved = new(bytes.Buffer) 492 } else { 493 saveXMLIndex = p.savedOffset() 494 } 495 } 496 } 497 } 498 } 499 500 // Find end element. 501 // Process sub-elements along the way. 502 Loop: 503 for { 504 var savedOffset int 505 if saveXML.IsValid() { 506 savedOffset = p.savedOffset() 507 } 508 tok, err := p.Token() 509 if err != nil { 510 return err 511 } 512 switch t := tok.(type) { 513 case StartElement: 514 consumed := false 515 if sv.IsValid() { 516 consumed, err = p.unmarshalPath(tinfo, sv, nil, &t) 517 if err != nil { 518 return err 519 } 520 if !consumed && saveAny.IsValid() { 521 consumed = true 522 if err := p.unmarshal(saveAny, &t); err != nil { 523 return err 524 } 525 } 526 } 527 if !consumed { 528 if err := p.Skip(); err != nil { 529 return err 530 } 531 } 532 533 case EndElement: 534 if saveXML.IsValid() { 535 saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset] 536 if saveXMLIndex == 0 { 537 p.saved = nil 538 } 539 } 540 break Loop 541 542 case CharData: 543 if saveData.IsValid() { 544 data = append(data, t...) 545 } 546 547 case Comment: 548 if saveComment.IsValid() { 549 comment = append(comment, t...) 550 } 551 } 552 } 553 554 if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) { 555 if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { 556 return err 557 } 558 saveData = reflect.Value{} 559 } 560 561 if saveData.IsValid() && saveData.CanAddr() { 562 pv := saveData.Addr() 563 if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { 564 if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { 565 return err 566 } 567 saveData = reflect.Value{} 568 } 569 } 570 571 if err := copyValue(saveData, data); err != nil { 572 return err 573 } 574 575 switch t := saveComment; t.Kind() { 576 case reflect.String: 577 t.SetString(string(comment)) 578 case reflect.Slice: 579 t.Set(reflect.ValueOf(comment)) 580 } 581 582 switch t := saveXML; t.Kind() { 583 case reflect.String: 584 t.SetString(string(saveXMLData)) 585 case reflect.Slice: 586 if t.Type().Elem().Kind() == reflect.Uint8 { 587 t.Set(reflect.ValueOf(saveXMLData)) 588 } 589 } 590 591 return nil 592 } 593 594 func copyValue(dst reflect.Value, src []byte) (err error) { 595 dst0 := dst 596 597 if dst.Kind() == reflect.Ptr { 598 if dst.IsNil() { 599 dst.Set(reflect.New(dst.Type().Elem())) 600 } 601 dst = dst.Elem() 602 } 603 604 // Save accumulated data. 605 switch dst.Kind() { 606 case reflect.Invalid: 607 // Probably a comment. 608 default: 609 return errors.New("cannot unmarshal into " + dst0.Type().String()) 610 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 611 itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits()) 612 if err != nil { 613 return err 614 } 615 dst.SetInt(itmp) 616 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 617 utmp, err := strconv.ParseUint(string(src), 10, dst.Type().Bits()) 618 if err != nil { 619 return err 620 } 621 dst.SetUint(utmp) 622 case reflect.Float32, reflect.Float64: 623 ftmp, err := strconv.ParseFloat(string(src), dst.Type().Bits()) 624 if err != nil { 625 return err 626 } 627 dst.SetFloat(ftmp) 628 case reflect.Bool: 629 value, err := strconv.ParseBool(strings.TrimSpace(string(src))) 630 if err != nil { 631 return err 632 } 633 dst.SetBool(value) 634 case reflect.String: 635 dst.SetString(string(src)) 636 case reflect.Slice: 637 if len(src) == 0 { 638 // non-nil to flag presence 639 src = []byte{} 640 } 641 dst.SetBytes(src) 642 } 643 return nil 644 } 645 646 // unmarshalPath walks down an XML structure looking for wanted 647 // paths, and calls unmarshal on them. 648 // The consumed result tells whether XML elements have been consumed 649 // from the Decoder until start's matching end element, or if it's 650 // still untouched because start is uninteresting for sv's fields. 651 func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) { 652 recurse := false 653 Loop: 654 for i := range tinfo.fields { 655 finfo := &tinfo.fields[i] 656 if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space { 657 continue 658 } 659 for j := range parents { 660 if parents[j] != finfo.parents[j] { 661 continue Loop 662 } 663 } 664 if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local { 665 // It's a perfect match, unmarshal the field. 666 return true, p.unmarshal(finfo.value(sv), start) 667 } 668 if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local { 669 // It's a prefix for the field. Break and recurse 670 // since it's not ok for one field path to be itself 671 // the prefix for another field path. 672 recurse = true 673 674 // We can reuse the same slice as long as we 675 // don't try to append to it. 676 parents = finfo.parents[:len(parents)+1] 677 break 678 } 679 } 680 if !recurse { 681 // We have no business with this element. 682 return false, nil 683 } 684 // The element is not a perfect match for any field, but one 685 // or more fields have the path to this element as a parent 686 // prefix. Recurse and attempt to match these. 687 for { 688 var tok Token 689 tok, err = p.Token() 690 if err != nil { 691 return true, err 692 } 693 switch t := tok.(type) { 694 case StartElement: 695 consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t) 696 if err != nil { 697 return true, err 698 } 699 if !consumed2 { 700 if err := p.Skip(); err != nil { 701 return true, err 702 } 703 } 704 case EndElement: 705 return true, nil 706 } 707 } 708 } 709 710 // Skip reads tokens until it has consumed the end element 711 // matching the most recent start element already consumed. 712 // It recurs if it encounters a start element, so it can be used to 713 // skip nested structures. 714 // It returns nil if it finds an end element matching the start 715 // element; otherwise it returns an error describing the problem. 716 func (d *Decoder) Skip() error { 717 for { 718 tok, err := d.Token() 719 if err != nil { 720 return err 721 } 722 switch tok.(type) { 723 case StartElement: 724 if err := d.Skip(); err != nil { 725 return err 726 } 727 case EndElement: 728 return nil 729 } 730 } 731 }