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