forked from subchen/go-xmldom
-
Notifications
You must be signed in to change notification settings - Fork 1
/
document.go
77 lines (68 loc) · 1.29 KB
/
document.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package xmldom
import (
"bytes"
)
const (
DEFAULT_XML_HEADER = `<?xml version="1.0" encoding="UTF-8"?>`
)
func NewDocument(name string) *Document {
d := &Document{
ProcInst: DEFAULT_XML_HEADER,
}
d.Root = &Node{
Document: d,
Name: name,
}
return d
}
type Document struct {
ProcInst string
Directives []string
NamespaceList []*Namespace
Root *Node
}
func (d *Document) getNamespaceByURI(uri string) *Namespace {
if uri == "" {
return nil
}
if d.NamespaceList != nil {
for _, ns := range d.NamespaceList {
if ns.URI == uri {
if ns.IsDefault() {
return nil
} else {
return ns
}
}
}
}
// create a new namespace
ns := &Namespace{
Name: uri,
URI: uri,
}
d.NamespaceList = append(d.NamespaceList, ns)
return ns
}
func (d *Document) XML() string {
buf := new(bytes.Buffer)
buf.WriteString(d.ProcInst)
for _, directive := range d.Directives {
buf.WriteString(directive)
}
buf.WriteString(d.Root.XML())
return buf.String()
}
func (d *Document) XMLPretty() string {
buf := new(bytes.Buffer)
if len(d.ProcInst) > 0 {
buf.WriteString(d.ProcInst)
buf.WriteByte('\n')
}
for _, directive := range d.Directives {
buf.WriteString(directive)
buf.WriteByte('\n')
}
buf.WriteString(d.Root.XMLPretty())
return buf.String()
}