forked from subchen/go-xmldom
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprint.go
76 lines (65 loc) · 1.33 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
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) {
pretty := len(indent) > 0
if pretty {
buf.WriteString(strings.Repeat(indent, level))
}
buf.WriteByte('<')
buf.WriteString(n.Name)
if len(n.Attributes) > 0 {
for _, attr := range n.Attributes {
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)
}
}
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("</")
buf.WriteString(n.Name)
buf.WriteByte('>')
if pretty {
buf.WriteByte('\n')
}
}