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