marshal.go 26 KB

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