encoder.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package xml
  2. // writer interface used by the xml encoder to write an encoded xml
  3. // document in a writer.
  4. type writer interface {
  5. // Write takes in a byte slice and returns number of bytes written and error
  6. Write(p []byte) (n int, err error)
  7. // WriteRune takes in a rune and returns number of bytes written and error
  8. WriteRune(r rune) (n int, err error)
  9. // WriteString takes in a string and returns number of bytes written and error
  10. WriteString(s string) (n int, err error)
  11. // String method returns a string
  12. String() string
  13. // Bytes return a byte slice.
  14. Bytes() []byte
  15. }
  16. // Encoder is an XML encoder that supports construction of XML values
  17. // using methods. The encoder takes in a writer and maintains a scratch buffer.
  18. type Encoder struct {
  19. w writer
  20. scratch *[]byte
  21. }
  22. // NewEncoder returns an XML encoder
  23. func NewEncoder(w writer) *Encoder {
  24. scratch := make([]byte, 64)
  25. return &Encoder{w: w, scratch: &scratch}
  26. }
  27. // String returns the string output of the XML encoder
  28. func (e Encoder) String() string {
  29. return e.w.String()
  30. }
  31. // Bytes returns the []byte slice of the XML encoder
  32. func (e Encoder) Bytes() []byte {
  33. return e.w.Bytes()
  34. }
  35. // RootElement builds a root element encoding
  36. // It writes it's start element tag. The value should be closed.
  37. func (e Encoder) RootElement(element StartElement) Value {
  38. return newValue(e.w, e.scratch, element)
  39. }