-
Notifications
You must be signed in to change notification settings - Fork 3
/
nodeutils.go
87 lines (81 loc) · 1.77 KB
/
nodeutils.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
package goxml
import (
"fmt"
"strings"
"github.com/wayf-dk/go-libxml2/types"
)
// RmElement removes an element in a Node
func RmElement(element types.Node) {
libxml2Lock.Lock()
defer libxml2Lock.Unlock()
parent, _ := element.ParentNode()
parent.RemoveChild(element)
element.Free()
}
func walk(n types.Node, level int) (pp string) {
switch n := n.(type) {
case types.Element:
tag := n.NodeName()
attrs := []string{}
namespaces, _ := n.GetNamespaces()
for _, ns := range namespaces {
prefix := "xmlns"
if ns.Prefix() != "" {
prefix = prefix + ":" + ns.Prefix()
}
attrs = append(attrs, prefix+"=\""+ns.URI()+"\"")
}
attributes, _ := n.Attributes()
for _, ats := range attributes {
attrs = append(attrs, strings.TrimSpace(ats.String()))
}
l := len(attrs)
x := ""
if l == 0 {
//x = ">"
} else if l > 0 {
x = " " + attrs[0]
attrs = attrs[1:]
if l == 1 {
//x += ">"
}
l--
}
pp = fmt.Sprintf("%*s<%s%s", level*4, "", tag, x)
x = ""
for i, attr := range attrs {
newline1 := "\n"
if i == l-1 {
//x = ">"
newline1 = ""
}
newline := ""
if i == 0 {
newline = "\n"
}
pp += fmt.Sprintf("%s%*s%s%s%s", newline, level*4+2+len(tag), "", attr, x, newline1)
}
children, _ := n.ChildNodes()
elements := false
subpp := ""
for _, c := range children {
_, ok := c.(types.Element)
elements = elements || ok
subpp += walk(c, level+1)
}
if elements {
pp += fmt.Sprintf(">\n%s%*s</%s>\n", subpp, level*4, "", n.NodeName())
} else {
if subpp == "" {
pp += "/>\n"
} else {
pp += fmt.Sprintf(">\n%*s%s\n%*s</%s>\n", level*5, "", subpp, level*4, "", n.NodeName())
}
}
case types.Node:
if txt := strings.TrimSpace(n.TextContent()); txt != "" {
pp = txt
}
}
return
}