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