forked from guonaihong/gout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml.go
62 lines (50 loc) · 972 Bytes
/
xml.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package encode
import (
"bytes"
"encoding/xml"
"errors"
"io"
"github.com/xishengcai/gout/core"
"github.com/xishengcai/gout/encoder"
)
var ErrNotXML = errors.New("Not xml data")
// XMLEncode xml encoder structure
type XMLEncode struct {
obj interface{}
}
// NewXMLEncode create a new xml encoder
func NewXMLEncode(obj interface{}) encoder.Encoder {
if obj == nil {
return nil
}
return &XMLEncode{obj: obj}
}
// Encode xml encoder
func (x *XMLEncode) Encode(w io.Writer) (err error) {
if v, ok := core.GetBytes(x.obj); ok {
if b := XMLValid(v); !b {
return ErrNotXML
}
_, err = w.Write(v)
return err
}
encode := xml.NewEncoder(w)
return encode.Encode(x.obj)
}
// Name xml Encoder name
func (x *XMLEncode) Name() string {
return "xml"
}
func XMLValid(b []byte) bool {
dec := xml.NewDecoder(bytes.NewBuffer(b))
for {
_, err := dec.Token()
if err != nil {
if err == io.EOF {
break
}
return false
}
}
return true
}