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