forked from subchen/go-xmldom
-
Notifications
You must be signed in to change notification settings - Fork 1
/
print.go
104 lines (92 loc) · 1.89 KB
/
print.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package xmldom
import (
"bytes"
"encoding/xml"
"fmt"
"strings"
)
func stringifyProcInst(pi *xml.ProcInst) string {
if pi == nil {
return ""
}
return fmt.Sprintf("<?%s %s?>", pi.Target, string(pi.Inst))
}
func stringifyDirective(directive *xml.Directive) string {
if directive == nil {
return ""
}
return fmt.Sprintf("<!%s>", string(*directive))
}
func printXML(buf *bytes.Buffer, n *Node, level int, indent string, withNS bool) {
pretty := len(indent) > 0
if pretty {
buf.WriteString(strings.Repeat(indent, level))
}
buf.WriteByte('<')
if n.NS != nil {
buf.WriteString(n.NS.Name)
buf.WriteByte(':')
}
buf.WriteString(n.Name)
if withNS {
for _, ns := range n.Document.NamespaceList {
if ns.Name != ns.URI {
buf.WriteString(" xmlns")
if ns.Name != "" {
buf.WriteByte(':')
buf.WriteString(ns.Name)
}
buf.WriteByte('=')
buf.WriteByte('"')
xml.Escape(buf, []byte(ns.URI))
buf.WriteByte('"')
}
}
}
if len(n.Attributes) > 0 {
for _, attr := range n.Attributes {
buf.WriteByte(' ')
if attr.NS != nil {
buf.WriteString(attr.NS.Name)
buf.WriteByte(':')
}
buf.WriteString(attr.Name)
buf.WriteByte('=')
buf.WriteByte('"')
xml.Escape(buf, []byte(attr.Value))
buf.WriteByte('"')
}
}
if len(n.Children) == 0 && len(n.Text) == 0 {
buf.WriteString(" />")
if pretty {
buf.WriteByte('\n')
}
return
}
buf.WriteByte('>')
if len(n.Children) > 0 {
if pretty {
buf.WriteByte('\n')
}
for _, c := range n.Children {
printXML(buf, c, level+1, indent, false)
}
}
if len(n.Text) > 0 {
xml.EscapeText(buf, []byte(n.Text))
}
if len(n.Children) > 0 && len(indent) > 0 {
buf.WriteString(strings.Repeat(indent, level))
}
buf.WriteString("</")
if n.NS != nil {
buf.WriteString(n.NS.Name)
buf.WriteByte(':')
}
buf.WriteString(n.Name)
buf.WriteByte('>')
if pretty {
buf.WriteByte('\n')
}
}