github.com/sbinet/go@v0.0.0-20160827155028-54d7de7dd62b/src/encoding/xml/marshal.go (about) 1 // Copyright 2011 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 "bufio" 9 "bytes" 10 "encoding" 11 "fmt" 12 "io" 13 "reflect" 14 "strconv" 15 "strings" 16 ) 17 18 const ( 19 // A generic XML header suitable for use with the output of Marshal. 20 // This is not automatically added to any output of this package, 21 // it is provided as a convenience. 22 Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n" 23 ) 24 25 // Marshal returns the XML encoding of v. 26 // 27 // Marshal handles an array or slice by marshalling each of the elements. 28 // Marshal handles a pointer by marshalling the value it points at or, if the 29 // pointer is nil, by writing nothing. Marshal handles an interface value by 30 // marshalling the value it contains or, if the interface value is nil, by 31 // writing nothing. Marshal handles all other data by writing one or more XML 32 // elements containing the data. 33 // 34 // The name for the XML elements is taken from, in order of preference: 35 // - the tag on the XMLName field, if the data is a struct 36 // - the value of the XMLName field of type Name 37 // - the tag of the struct field used to obtain the data 38 // - the name of the struct field used to obtain the data 39 // - the name of the marshalled type 40 // 41 // The XML element for a struct contains marshalled elements for each of the 42 // exported fields of the struct, with these exceptions: 43 // - the XMLName field, described above, is omitted. 44 // - a field with tag "-" is omitted. 45 // - a field with tag "name,attr" becomes an attribute with 46 // the given name in the XML element. 47 // - a field with tag ",attr" becomes an attribute with the 48 // field name in the XML element. 49 // - a field with tag ",chardata" is written as character data, 50 // not as an XML element. 51 // - a field with tag ",cdata" is written as character data 52 // wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element. 53 // - a field with tag ",innerxml" is written verbatim, not subject 54 // to the usual marshalling procedure. 55 // - a field with tag ",comment" is written as an XML comment, not 56 // subject to the usual marshalling procedure. It must not contain 57 // the "--" string within it. 58 // - a field with a tag including the "omitempty" option is omitted 59 // if the field value is empty. The empty values are false, 0, any 60 // nil pointer or interface value, and any array, slice, map, or 61 // string of length zero. 62 // - an anonymous struct field is handled as if the fields of its 63 // value were part of the outer struct. 64 // 65 // If a field uses a tag "a>b>c", then the element c will be nested inside 66 // parent elements a and b. Fields that appear next to each other that name 67 // the same parent will be enclosed in one XML element. 68 // 69 // See MarshalIndent for an example. 70 // 71 // Marshal will return an error if asked to marshal a channel, function, or map. 72 func Marshal(v interface{}) ([]byte, error) { 73 var b bytes.Buffer 74 if err := NewEncoder(&b).Encode(v); err != nil { 75 return nil, err 76 } 77 return b.Bytes(), nil 78 } 79 80 // Marshaler is the interface implemented by objects that can marshal 81 // themselves into valid XML elements. 82 // 83 // MarshalXML encodes the receiver as zero or more XML elements. 84 // By convention, arrays or slices are typically encoded as a sequence 85 // of elements, one per entry. 86 // Using start as the element tag is not required, but doing so 87 // will enable Unmarshal to match the XML elements to the correct 88 // struct field. 89 // One common implementation strategy is to construct a separate 90 // value with a layout corresponding to the desired XML and then 91 // to encode it using e.EncodeElement. 92 // Another common strategy is to use repeated calls to e.EncodeToken 93 // to generate the XML output one token at a time. 94 // The sequence of encoded tokens must make up zero or more valid 95 // XML elements. 96 type Marshaler interface { 97 MarshalXML(e *Encoder, start StartElement) error 98 } 99 100 // MarshalerAttr is the interface implemented by objects that can marshal 101 // themselves into valid XML attributes. 102 // 103 // MarshalXMLAttr returns an XML attribute with the encoded value of the receiver. 104 // Using name as the attribute name is not required, but doing so 105 // will enable Unmarshal to match the attribute to the correct 106 // struct field. 107 // If MarshalXMLAttr returns the zero attribute Attr{}, no attribute 108 // will be generated in the output. 109 // MarshalXMLAttr is used only for struct fields with the 110 // "attr" option in the field tag. 111 type MarshalerAttr interface { 112 MarshalXMLAttr(name Name) (Attr, error) 113 } 114 115 // MarshalIndent works like Marshal, but each XML element begins on a new 116 // indented line that starts with prefix and is followed by one or more 117 // copies of indent according to the nesting depth. 118 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { 119 var b bytes.Buffer 120 enc := NewEncoder(&b) 121 enc.Indent(prefix, indent) 122 if err := enc.Encode(v); err != nil { 123 return nil, err 124 } 125 return b.Bytes(), nil 126 } 127 128 // An Encoder writes XML data to an output stream. 129 type Encoder struct { 130 p printer 131 } 132 133 // NewEncoder returns a new encoder that writes to w. 134 func NewEncoder(w io.Writer) *Encoder { 135 e := &Encoder{printer{Writer: bufio.NewWriter(w)}} 136 e.p.encoder = e 137 return e 138 } 139 140 // Indent sets the encoder to generate XML in which each element 141 // begins on a new indented line that starts with prefix and is followed by 142 // one or more copies of indent according to the nesting depth. 143 func (enc *Encoder) Indent(prefix, indent string) { 144 enc.p.prefix = prefix 145 enc.p.indent = indent 146 } 147 148 // Encode writes the XML encoding of v to the stream. 149 // 150 // See the documentation for Marshal for details about the conversion 151 // of Go values to XML. 152 // 153 // Encode calls Flush before returning. 154 func (enc *Encoder) Encode(v interface{}) error { 155 err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil) 156 if err != nil { 157 return err 158 } 159 return enc.p.Flush() 160 } 161 162 // EncodeElement writes the XML encoding of v to the stream, 163 // using start as the outermost tag in the encoding. 164 // 165 // See the documentation for Marshal for details about the conversion 166 // of Go values to XML. 167 // 168 // EncodeElement calls Flush before returning. 169 func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error { 170 err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start) 171 if err != nil { 172 return err 173 } 174 return enc.p.Flush() 175 } 176 177 var ( 178 begComment = []byte("<!--") 179 endComment = []byte("-->") 180 endProcInst = []byte("?>") 181 ) 182 183 // EncodeToken writes the given XML token to the stream. 184 // It returns an error if StartElement and EndElement tokens are not properly matched. 185 // 186 // EncodeToken does not call Flush, because usually it is part of a larger operation 187 // such as Encode or EncodeElement (or a custom Marshaler's MarshalXML invoked 188 // during those), and those will call Flush when finished. 189 // Callers that create an Encoder and then invoke EncodeToken directly, without 190 // using Encode or EncodeElement, need to call Flush when finished to ensure 191 // that the XML is written to the underlying writer. 192 // 193 // EncodeToken allows writing a ProcInst with Target set to "xml" only as the first token 194 // in the stream. 195 func (enc *Encoder) EncodeToken(t Token) error { 196 197 p := &enc.p 198 switch t := t.(type) { 199 case StartElement: 200 if err := p.writeStart(&t); err != nil { 201 return err 202 } 203 case EndElement: 204 if err := p.writeEnd(t.Name); err != nil { 205 return err 206 } 207 case CharData: 208 escapeText(p, t, false) 209 case Comment: 210 if bytes.Contains(t, endComment) { 211 return fmt.Errorf("xml: EncodeToken of Comment containing --> marker") 212 } 213 p.WriteString("<!--") 214 p.Write(t) 215 p.WriteString("-->") 216 return p.cachedWriteError() 217 case ProcInst: 218 // First token to be encoded which is also a ProcInst with target of xml 219 // is the xml declaration. The only ProcInst where target of xml is allowed. 220 if t.Target == "xml" && p.Buffered() != 0 { 221 return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded") 222 } 223 if !isNameString(t.Target) { 224 return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target") 225 } 226 if bytes.Contains(t.Inst, endProcInst) { 227 return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker") 228 } 229 p.WriteString("<?") 230 p.WriteString(t.Target) 231 if len(t.Inst) > 0 { 232 p.WriteByte(' ') 233 p.Write(t.Inst) 234 } 235 p.WriteString("?>") 236 case Directive: 237 if !isValidDirective(t) { 238 return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers") 239 } 240 p.WriteString("<!") 241 p.Write(t) 242 p.WriteString(">") 243 default: 244 return fmt.Errorf("xml: EncodeToken of invalid token type") 245 246 } 247 return p.cachedWriteError() 248 } 249 250 // isValidDirective reports whether dir is a valid directive text, 251 // meaning angle brackets are matched, ignoring comments and strings. 252 func isValidDirective(dir Directive) bool { 253 var ( 254 depth int 255 inquote uint8 256 incomment bool 257 ) 258 for i, c := range dir { 259 switch { 260 case incomment: 261 if c == '>' { 262 if n := 1 + i - len(endComment); n >= 0 && bytes.Equal(dir[n:i+1], endComment) { 263 incomment = false 264 } 265 } 266 // Just ignore anything in comment 267 case inquote != 0: 268 if c == inquote { 269 inquote = 0 270 } 271 // Just ignore anything within quotes 272 case c == '\'' || c == '"': 273 inquote = c 274 case c == '<': 275 if i+len(begComment) < len(dir) && bytes.Equal(dir[i:i+len(begComment)], begComment) { 276 incomment = true 277 } else { 278 depth++ 279 } 280 case c == '>': 281 if depth == 0 { 282 return false 283 } 284 depth-- 285 } 286 } 287 return depth == 0 && inquote == 0 && !incomment 288 } 289 290 // Flush flushes any buffered XML to the underlying writer. 291 // See the EncodeToken documentation for details about when it is necessary. 292 func (enc *Encoder) Flush() error { 293 return enc.p.Flush() 294 } 295 296 type printer struct { 297 *bufio.Writer 298 encoder *Encoder 299 seq int 300 indent string 301 prefix string 302 depth int 303 indentedIn bool 304 putNewline bool 305 attrNS map[string]string // map prefix -> name space 306 attrPrefix map[string]string // map name space -> prefix 307 prefixes []string 308 tags []Name 309 } 310 311 // createAttrPrefix finds the name space prefix attribute to use for the given name space, 312 // defining a new prefix if necessary. It returns the prefix. 313 func (p *printer) createAttrPrefix(url string) string { 314 if prefix := p.attrPrefix[url]; prefix != "" { 315 return prefix 316 } 317 318 // The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml" 319 // and must be referred to that way. 320 // (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns", 321 // but users should not be trying to use that one directly - that's our job.) 322 if url == xmlURL { 323 return "xml" 324 } 325 326 // Need to define a new name space. 327 if p.attrPrefix == nil { 328 p.attrPrefix = make(map[string]string) 329 p.attrNS = make(map[string]string) 330 } 331 332 // Pick a name. We try to use the final element of the path 333 // but fall back to _. 334 prefix := strings.TrimRight(url, "/") 335 if i := strings.LastIndex(prefix, "/"); i >= 0 { 336 prefix = prefix[i+1:] 337 } 338 if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") { 339 prefix = "_" 340 } 341 if strings.HasPrefix(prefix, "xml") { 342 // xmlanything is reserved. 343 prefix = "_" + prefix 344 } 345 if p.attrNS[prefix] != "" { 346 // Name is taken. Find a better one. 347 for p.seq++; ; p.seq++ { 348 if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" { 349 prefix = id 350 break 351 } 352 } 353 } 354 355 p.attrPrefix[url] = prefix 356 p.attrNS[prefix] = url 357 358 p.WriteString(`xmlns:`) 359 p.WriteString(prefix) 360 p.WriteString(`="`) 361 EscapeText(p, []byte(url)) 362 p.WriteString(`" `) 363 364 p.prefixes = append(p.prefixes, prefix) 365 366 return prefix 367 } 368 369 // deleteAttrPrefix removes an attribute name space prefix. 370 func (p *printer) deleteAttrPrefix(prefix string) { 371 delete(p.attrPrefix, p.attrNS[prefix]) 372 delete(p.attrNS, prefix) 373 } 374 375 func (p *printer) markPrefix() { 376 p.prefixes = append(p.prefixes, "") 377 } 378 379 func (p *printer) popPrefix() { 380 for len(p.prefixes) > 0 { 381 prefix := p.prefixes[len(p.prefixes)-1] 382 p.prefixes = p.prefixes[:len(p.prefixes)-1] 383 if prefix == "" { 384 break 385 } 386 p.deleteAttrPrefix(prefix) 387 } 388 } 389 390 var ( 391 marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() 392 marshalerAttrType = reflect.TypeOf((*MarshalerAttr)(nil)).Elem() 393 textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() 394 ) 395 396 // marshalValue writes one or more XML elements representing val. 397 // If val was obtained from a struct field, finfo must have its details. 398 func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error { 399 if startTemplate != nil && startTemplate.Name.Local == "" { 400 return fmt.Errorf("xml: EncodeElement of StartElement with missing name") 401 } 402 403 if !val.IsValid() { 404 return nil 405 } 406 if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) { 407 return nil 408 } 409 410 // Drill into interfaces and pointers. 411 // This can turn into an infinite loop given a cyclic chain, 412 // but it matches the Go 1 behavior. 413 for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { 414 if val.IsNil() { 415 return nil 416 } 417 val = val.Elem() 418 } 419 420 kind := val.Kind() 421 typ := val.Type() 422 423 // Check for marshaler. 424 if val.CanInterface() && typ.Implements(marshalerType) { 425 return p.marshalInterface(val.Interface().(Marshaler), defaultStart(typ, finfo, startTemplate)) 426 } 427 if val.CanAddr() { 428 pv := val.Addr() 429 if pv.CanInterface() && pv.Type().Implements(marshalerType) { 430 return p.marshalInterface(pv.Interface().(Marshaler), defaultStart(pv.Type(), finfo, startTemplate)) 431 } 432 } 433 434 // Check for text marshaler. 435 if val.CanInterface() && typ.Implements(textMarshalerType) { 436 return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), defaultStart(typ, finfo, startTemplate)) 437 } 438 if val.CanAddr() { 439 pv := val.Addr() 440 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { 441 return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), defaultStart(pv.Type(), finfo, startTemplate)) 442 } 443 } 444 445 // Slices and arrays iterate over the elements. They do not have an enclosing tag. 446 if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 { 447 for i, n := 0, val.Len(); i < n; i++ { 448 if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil { 449 return err 450 } 451 } 452 return nil 453 } 454 455 tinfo, err := getTypeInfo(typ) 456 if err != nil { 457 return err 458 } 459 460 // Create start element. 461 // Precedence for the XML element name is: 462 // 0. startTemplate 463 // 1. XMLName field in underlying struct; 464 // 2. field name/tag in the struct field; and 465 // 3. type name 466 var start StartElement 467 468 if startTemplate != nil { 469 start.Name = startTemplate.Name 470 start.Attr = append(start.Attr, startTemplate.Attr...) 471 } else if tinfo.xmlname != nil { 472 xmlname := tinfo.xmlname 473 if xmlname.name != "" { 474 start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name 475 } else if v, ok := xmlname.value(val).Interface().(Name); ok && v.Local != "" { 476 start.Name = v 477 } 478 } 479 if start.Name.Local == "" && finfo != nil { 480 start.Name.Space, start.Name.Local = finfo.xmlns, finfo.name 481 } 482 if start.Name.Local == "" { 483 name := typ.Name() 484 if name == "" { 485 return &UnsupportedTypeError{typ} 486 } 487 start.Name.Local = name 488 } 489 490 // Attributes 491 for i := range tinfo.fields { 492 finfo := &tinfo.fields[i] 493 if finfo.flags&fAttr == 0 { 494 continue 495 } 496 fv := finfo.value(val) 497 name := Name{Space: finfo.xmlns, Local: finfo.name} 498 499 if finfo.flags&fOmitEmpty != 0 && isEmptyValue(fv) { 500 continue 501 } 502 503 if fv.Kind() == reflect.Interface && fv.IsNil() { 504 continue 505 } 506 507 if fv.CanInterface() && fv.Type().Implements(marshalerAttrType) { 508 attr, err := fv.Interface().(MarshalerAttr).MarshalXMLAttr(name) 509 if err != nil { 510 return err 511 } 512 if attr.Name.Local != "" { 513 start.Attr = append(start.Attr, attr) 514 } 515 continue 516 } 517 518 if fv.CanAddr() { 519 pv := fv.Addr() 520 if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) { 521 attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name) 522 if err != nil { 523 return err 524 } 525 if attr.Name.Local != "" { 526 start.Attr = append(start.Attr, attr) 527 } 528 continue 529 } 530 } 531 532 if fv.CanInterface() && fv.Type().Implements(textMarshalerType) { 533 text, err := fv.Interface().(encoding.TextMarshaler).MarshalText() 534 if err != nil { 535 return err 536 } 537 start.Attr = append(start.Attr, Attr{name, string(text)}) 538 continue 539 } 540 541 if fv.CanAddr() { 542 pv := fv.Addr() 543 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { 544 text, err := pv.Interface().(encoding.TextMarshaler).MarshalText() 545 if err != nil { 546 return err 547 } 548 start.Attr = append(start.Attr, Attr{name, string(text)}) 549 continue 550 } 551 } 552 553 // Dereference or skip nil pointer, interface values. 554 switch fv.Kind() { 555 case reflect.Ptr, reflect.Interface: 556 if fv.IsNil() { 557 continue 558 } 559 fv = fv.Elem() 560 } 561 562 s, b, err := p.marshalSimple(fv.Type(), fv) 563 if err != nil { 564 return err 565 } 566 if b != nil { 567 s = string(b) 568 } 569 start.Attr = append(start.Attr, Attr{name, s}) 570 } 571 572 if err := p.writeStart(&start); err != nil { 573 return err 574 } 575 576 if val.Kind() == reflect.Struct { 577 err = p.marshalStruct(tinfo, val) 578 } else { 579 s, b, err1 := p.marshalSimple(typ, val) 580 if err1 != nil { 581 err = err1 582 } else if b != nil { 583 EscapeText(p, b) 584 } else { 585 p.EscapeString(s) 586 } 587 } 588 if err != nil { 589 return err 590 } 591 592 if err := p.writeEnd(start.Name); err != nil { 593 return err 594 } 595 596 return p.cachedWriteError() 597 } 598 599 // defaultStart returns the default start element to use, 600 // given the reflect type, field info, and start template. 601 func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement { 602 var start StartElement 603 // Precedence for the XML element name is as above, 604 // except that we do not look inside structs for the first field. 605 if startTemplate != nil { 606 start.Name = startTemplate.Name 607 start.Attr = append(start.Attr, startTemplate.Attr...) 608 } else if finfo != nil && finfo.name != "" { 609 start.Name.Local = finfo.name 610 start.Name.Space = finfo.xmlns 611 } else if typ.Name() != "" { 612 start.Name.Local = typ.Name() 613 } else { 614 // Must be a pointer to a named type, 615 // since it has the Marshaler methods. 616 start.Name.Local = typ.Elem().Name() 617 } 618 return start 619 } 620 621 // marshalInterface marshals a Marshaler interface value. 622 func (p *printer) marshalInterface(val Marshaler, start StartElement) error { 623 // Push a marker onto the tag stack so that MarshalXML 624 // cannot close the XML tags that it did not open. 625 p.tags = append(p.tags, Name{}) 626 n := len(p.tags) 627 628 err := val.MarshalXML(p.encoder, start) 629 if err != nil { 630 return err 631 } 632 633 // Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark. 634 if len(p.tags) > n { 635 return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local) 636 } 637 p.tags = p.tags[:n-1] 638 return nil 639 } 640 641 // marshalTextInterface marshals a TextMarshaler interface value. 642 func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error { 643 if err := p.writeStart(&start); err != nil { 644 return err 645 } 646 text, err := val.MarshalText() 647 if err != nil { 648 return err 649 } 650 EscapeText(p, text) 651 return p.writeEnd(start.Name) 652 } 653 654 // writeStart writes the given start element. 655 func (p *printer) writeStart(start *StartElement) error { 656 if start.Name.Local == "" { 657 return fmt.Errorf("xml: start tag with no name") 658 } 659 660 p.tags = append(p.tags, start.Name) 661 p.markPrefix() 662 663 p.writeIndent(1) 664 p.WriteByte('<') 665 p.WriteString(start.Name.Local) 666 667 if start.Name.Space != "" { 668 p.WriteString(` xmlns="`) 669 p.EscapeString(start.Name.Space) 670 p.WriteByte('"') 671 } 672 673 // Attributes 674 for _, attr := range start.Attr { 675 name := attr.Name 676 if name.Local == "" { 677 continue 678 } 679 p.WriteByte(' ') 680 if name.Space != "" { 681 p.WriteString(p.createAttrPrefix(name.Space)) 682 p.WriteByte(':') 683 } 684 p.WriteString(name.Local) 685 p.WriteString(`="`) 686 p.EscapeString(attr.Value) 687 p.WriteByte('"') 688 } 689 p.WriteByte('>') 690 return nil 691 } 692 693 func (p *printer) writeEnd(name Name) error { 694 if name.Local == "" { 695 return fmt.Errorf("xml: end tag with no name") 696 } 697 if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" { 698 return fmt.Errorf("xml: end tag </%s> without start tag", name.Local) 699 } 700 if top := p.tags[len(p.tags)-1]; top != name { 701 if top.Local != name.Local { 702 return fmt.Errorf("xml: end tag </%s> does not match start tag <%s>", name.Local, top.Local) 703 } 704 return fmt.Errorf("xml: end tag </%s> in namespace %s does not match start tag <%s> in namespace %s", name.Local, name.Space, top.Local, top.Space) 705 } 706 p.tags = p.tags[:len(p.tags)-1] 707 708 p.writeIndent(-1) 709 p.WriteByte('<') 710 p.WriteByte('/') 711 p.WriteString(name.Local) 712 p.WriteByte('>') 713 p.popPrefix() 714 return nil 715 } 716 717 func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) { 718 switch val.Kind() { 719 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 720 return strconv.FormatInt(val.Int(), 10), nil, nil 721 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 722 return strconv.FormatUint(val.Uint(), 10), nil, nil 723 case reflect.Float32, reflect.Float64: 724 return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil 725 case reflect.String: 726 return val.String(), nil, nil 727 case reflect.Bool: 728 return strconv.FormatBool(val.Bool()), nil, nil 729 case reflect.Array: 730 if typ.Elem().Kind() != reflect.Uint8 { 731 break 732 } 733 // [...]byte 734 var bytes []byte 735 if val.CanAddr() { 736 bytes = val.Slice(0, val.Len()).Bytes() 737 } else { 738 bytes = make([]byte, val.Len()) 739 reflect.Copy(reflect.ValueOf(bytes), val) 740 } 741 return "", bytes, nil 742 case reflect.Slice: 743 if typ.Elem().Kind() != reflect.Uint8 { 744 break 745 } 746 // []byte 747 return "", val.Bytes(), nil 748 } 749 return "", nil, &UnsupportedTypeError{typ} 750 } 751 752 var ddBytes = []byte("--") 753 754 func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error { 755 s := parentStack{p: p} 756 for i := range tinfo.fields { 757 finfo := &tinfo.fields[i] 758 if finfo.flags&fAttr != 0 { 759 continue 760 } 761 vf := finfo.value(val) 762 763 // Dereference or skip nil pointer, interface values. 764 switch vf.Kind() { 765 case reflect.Ptr, reflect.Interface: 766 if !vf.IsNil() { 767 vf = vf.Elem() 768 } 769 } 770 771 switch finfo.flags & fMode { 772 case fCDATA, fCharData: 773 emit := EscapeText 774 if finfo.flags&fMode == fCDATA { 775 emit = emitCDATA 776 } 777 if err := s.trim(finfo.parents); err != nil { 778 return err 779 } 780 if vf.CanInterface() && vf.Type().Implements(textMarshalerType) { 781 data, err := vf.Interface().(encoding.TextMarshaler).MarshalText() 782 if err != nil { 783 return err 784 } 785 if err := emit(p, data); err != nil { 786 return err 787 } 788 continue 789 } 790 if vf.CanAddr() { 791 pv := vf.Addr() 792 if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { 793 data, err := pv.Interface().(encoding.TextMarshaler).MarshalText() 794 if err != nil { 795 return err 796 } 797 if err := emit(p, data); err != nil { 798 return err 799 } 800 continue 801 } 802 } 803 var scratch [64]byte 804 switch vf.Kind() { 805 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 806 if err := emit(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)); err != nil { 807 return err 808 } 809 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 810 if err := emit(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)); err != nil { 811 return err 812 } 813 case reflect.Float32, reflect.Float64: 814 if err := emit(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())); err != nil { 815 return err 816 } 817 case reflect.Bool: 818 if err := emit(p, strconv.AppendBool(scratch[:0], vf.Bool())); err != nil { 819 return err 820 } 821 case reflect.String: 822 if err := emit(p, []byte(vf.String())); err != nil { 823 return err 824 } 825 case reflect.Slice: 826 if elem, ok := vf.Interface().([]byte); ok { 827 if err := emit(p, elem); err != nil { 828 return err 829 } 830 } 831 } 832 continue 833 834 case fComment: 835 if err := s.trim(finfo.parents); err != nil { 836 return err 837 } 838 k := vf.Kind() 839 if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) { 840 return fmt.Errorf("xml: bad type for comment field of %s", val.Type()) 841 } 842 if vf.Len() == 0 { 843 continue 844 } 845 p.writeIndent(0) 846 p.WriteString("<!--") 847 dashDash := false 848 dashLast := false 849 switch k { 850 case reflect.String: 851 s := vf.String() 852 dashDash = strings.Contains(s, "--") 853 dashLast = s[len(s)-1] == '-' 854 if !dashDash { 855 p.WriteString(s) 856 } 857 case reflect.Slice: 858 b := vf.Bytes() 859 dashDash = bytes.Contains(b, ddBytes) 860 dashLast = b[len(b)-1] == '-' 861 if !dashDash { 862 p.Write(b) 863 } 864 default: 865 panic("can't happen") 866 } 867 if dashDash { 868 return fmt.Errorf(`xml: comments must not contain "--"`) 869 } 870 if dashLast { 871 // "--->" is invalid grammar. Make it "- -->" 872 p.WriteByte(' ') 873 } 874 p.WriteString("-->") 875 continue 876 877 case fInnerXml: 878 iface := vf.Interface() 879 switch raw := iface.(type) { 880 case []byte: 881 p.Write(raw) 882 continue 883 case string: 884 p.WriteString(raw) 885 continue 886 } 887 888 case fElement, fElement | fAny: 889 if err := s.trim(finfo.parents); err != nil { 890 return err 891 } 892 if len(finfo.parents) > len(s.stack) { 893 if vf.Kind() != reflect.Ptr && vf.Kind() != reflect.Interface || !vf.IsNil() { 894 if err := s.push(finfo.parents[len(s.stack):]); err != nil { 895 return err 896 } 897 } 898 } 899 } 900 if err := p.marshalValue(vf, finfo, nil); err != nil { 901 return err 902 } 903 } 904 s.trim(nil) 905 return p.cachedWriteError() 906 } 907 908 // return the bufio Writer's cached write error 909 func (p *printer) cachedWriteError() error { 910 _, err := p.Write(nil) 911 return err 912 } 913 914 func (p *printer) writeIndent(depthDelta int) { 915 if len(p.prefix) == 0 && len(p.indent) == 0 { 916 return 917 } 918 if depthDelta < 0 { 919 p.depth-- 920 if p.indentedIn { 921 p.indentedIn = false 922 return 923 } 924 p.indentedIn = false 925 } 926 if p.putNewline { 927 p.WriteByte('\n') 928 } else { 929 p.putNewline = true 930 } 931 if len(p.prefix) > 0 { 932 p.WriteString(p.prefix) 933 } 934 if len(p.indent) > 0 { 935 for i := 0; i < p.depth; i++ { 936 p.WriteString(p.indent) 937 } 938 } 939 if depthDelta > 0 { 940 p.depth++ 941 p.indentedIn = true 942 } 943 } 944 945 type parentStack struct { 946 p *printer 947 stack []string 948 } 949 950 // trim updates the XML context to match the longest common prefix of the stack 951 // and the given parents. A closing tag will be written for every parent 952 // popped. Passing a zero slice or nil will close all the elements. 953 func (s *parentStack) trim(parents []string) error { 954 split := 0 955 for ; split < len(parents) && split < len(s.stack); split++ { 956 if parents[split] != s.stack[split] { 957 break 958 } 959 } 960 for i := len(s.stack) - 1; i >= split; i-- { 961 if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil { 962 return err 963 } 964 } 965 s.stack = s.stack[:split] 966 return nil 967 } 968 969 // push adds parent elements to the stack and writes open tags. 970 func (s *parentStack) push(parents []string) error { 971 for i := 0; i < len(parents); i++ { 972 if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil { 973 return err 974 } 975 } 976 s.stack = append(s.stack, parents...) 977 return nil 978 } 979 980 // A MarshalXMLError is returned when Marshal encounters a type 981 // that cannot be converted into XML. 982 type UnsupportedTypeError struct { 983 Type reflect.Type 984 } 985 986 func (e *UnsupportedTypeError) Error() string { 987 return "xml: unsupported type: " + e.Type.String() 988 } 989 990 func isEmptyValue(v reflect.Value) bool { 991 switch v.Kind() { 992 case reflect.Array, reflect.Map, reflect.Slice, reflect.String: 993 return v.Len() == 0 994 case reflect.Bool: 995 return !v.Bool() 996 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 997 return v.Int() == 0 998 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 999 return v.Uint() == 0 1000 case reflect.Float32, reflect.Float64: 1001 return v.Float() == 0 1002 case reflect.Interface, reflect.Ptr: 1003 return v.IsNil() 1004 } 1005 return false 1006 }