File: node.go

package info (click to toggle)
golang-github-antchfx-xmlquery 1.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 200 kB
  • sloc: makefile: 2
file content (526 lines) | stat: -rw-r--r-- 12,110 bytes parent folder | download
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
package xmlquery

import (
	"bufio"
	"encoding/xml"
	"fmt"
	"html"
	"io"
	"strings"
)

// A NodeType is the type of a Node.
type NodeType uint

const (
	// DocumentNode is a document object that, as the root of the document tree,
	// provides access to the entire XML document.
	DocumentNode NodeType = iota
	// DeclarationNode is the document type declaration, indicated by the
	// following tag (for example, <!DOCTYPE...> ).
	DeclarationNode
	// ElementNode is an element (for example, <item> ).
	ElementNode
	// TextNode is the text content of a node.
	TextNode
	// CharDataNode node <![CDATA[content]]>
	CharDataNode
	// CommentNode a comment (for example, <!-- my comment --> ).
	CommentNode
	// AttributeNode is an attribute of element.
	AttributeNode
	// NotationNode is a directive represents in document (for example, <!text...>).
	NotationNode
	// ProcessingInstruction represents an XML processing instruction (e.g., <?target instruction?>).
	ProcessingInstruction
)

type Attr struct {
	Name         xml.Name
	Value        string
	NamespaceURI string
}

// ProcInstData represents an XML processing instruction.
type ProcInstData struct {
	Target string
	Inst   string
}

// A Node consists of a NodeType and some Data (tag name for
// element nodes, content for text) and are part of a tree of Nodes.
type Node struct {
	Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node

	Type         NodeType
	Data         string
	Prefix       string
	NamespaceURI string
	Attr         []Attr
	ProcInst     *ProcInstData

	level      int // node level in the tree
	LineNumber int // line number where this node appears in the source XML
}

type outputConfiguration struct {
	printSelf              bool
	preserveSpaces         bool
	emptyElementTagSupport bool
	skipComments           bool
	useIndentation         string
}

type OutputOption func(*outputConfiguration)

// WithOutputSelf configures the Node to print the root node itself
func WithOutputSelf() OutputOption {
	return func(oc *outputConfiguration) {
		oc.printSelf = true
	}
}

// WithEmptyTagSupport empty tags should be written as <empty/> and
// not as <empty></empty>
func WithEmptyTagSupport() OutputOption {
	return func(oc *outputConfiguration) {
		oc.emptyElementTagSupport = true
	}
}

// WithoutComments will skip comments in output
func WithoutComments() OutputOption {
	return func(oc *outputConfiguration) {
		oc.skipComments = true
	}
}

// WithPreserveSpace will preserve spaces in output
func WithPreserveSpace() OutputOption {
	return func(oc *outputConfiguration) {
		oc.preserveSpaces = true
	}
}

// WithoutPreserveSpace will not preserve spaces in output
func WithoutPreserveSpace() OutputOption {
	return func(oc *outputConfiguration) {
		oc.preserveSpaces = false
	}
}

// WithIndentation sets the indentation string used for formatting the output.
func WithIndentation(indentation string) OutputOption {
	return func(oc *outputConfiguration) {
		oc.useIndentation = indentation
	}
}

func newXMLName(name string) xml.Name {
	if i := strings.IndexByte(name, ':'); i > 0 {
		return xml.Name{
			Space: name[:i],
			Local: name[i+1:],
		}
	}
	return xml.Name{
		Local: name,
	}
}

func (n *Node) Level() int {
	return n.level
}

// GetLineNumber returns the line number where this node appears in the source XML.
func (n *Node) GetLineNumber() int {
	return n.LineNumber
}

// InnerText returns the text between the start and end tags of the object.
func (n *Node) InnerText() string {
	var output func(*strings.Builder, *Node)
	output = func(b *strings.Builder, n *Node) {
		switch n.Type {
		case TextNode, CharDataNode:
			b.WriteString(n.Data)
		case CommentNode:
		default:
			for child := n.FirstChild; child != nil; child = child.NextSibling {
				output(b, child)
			}
		}
	}

	var b strings.Builder
	output(&b, n)
	return b.String()
}

// ChildNodes returns all the child nodes of the current node,
// including text, comments, and char data.
func (n *Node) ChildNodes() []*Node {
	var list []*Node
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		list = append(list, child)
	}
	return list
}

func (n *Node) sanitizedData(preserveSpaces bool) string {
	if preserveSpaces {
		return n.Data
	}
	return strings.TrimSpace(n.Data)
}

func calculatePreserveSpaces(n *Node, pastValue bool) bool {
	if attr := n.SelectAttr("xml:space"); attr == "preserve" {
		return true
	} else if attr == "default" {
		return false
	}
	return pastValue
}

type indentation struct {
	level    int
	hasChild bool
	indent   string
	w        io.Writer
}

func newIndentation(indent string, w io.Writer) *indentation {
	if indent == "" {
		return nil
	}
	return &indentation{
		indent: indent,
		w:      w,
	}
}

func (i *indentation) NewLine() (err error) {
	if i == nil {
		return
	}
	_, err = io.WriteString(i.w, "\n")
	return
}

func (i *indentation) Open() (err error) {
	if i == nil {
		return
	}

	if err = i.writeIndent(); err != nil {
		return
	}

	i.level++
	i.hasChild = false
	return
}

func (i *indentation) Close() (err error) {
	if i == nil {
		return
	}
	i.level--
	if i.hasChild {
		if err = i.writeIndent(); err != nil {
			return
		}
	}
	i.hasChild = true
	return
}

func (i *indentation) writeIndent() (err error) {
	_, err = io.WriteString(i.w, "\n")
	if err != nil {
		return
	}
	_, err = io.WriteString(i.w, strings.Repeat(i.indent, i.level))
	return
}

func outputXML(w io.Writer, n *Node, preserveSpaces bool, config *outputConfiguration, indent *indentation) (err error) {
	preserveSpaces = calculatePreserveSpaces(n, preserveSpaces)
	switch n.Type {
	case TextNode:
		_, err = io.WriteString(w, html.EscapeString(n.sanitizedData(preserveSpaces)))
		return
	case CharDataNode:
		_, err = fmt.Fprintf(w, "<![CDATA[%v]]>", n.Data)
		return
	case CommentNode:
		if !config.skipComments {
			_, err = fmt.Fprintf(w, "<!--%v-->", n.Data)
		}
		return
	case NotationNode:
		if err = indent.NewLine(); err != nil {
			return
		}
		_, err = fmt.Fprintf(w, "<!%s>", n.Data)
		return
	case DeclarationNode:
		_, err = io.WriteString(w, "<?"+n.Data)
		if err != nil {
			return
		}
	case ProcessingInstruction:
		if len(n.ProcInst.Inst) > 0 {
			_, err = fmt.Fprintf(w, "<?%s %s?>", n.ProcInst.Target, n.ProcInst.Inst)
		} else {
			_, err = fmt.Fprintf(w, "<?%s?>", n.ProcInst.Target)
		}
		return
	default:
		if err = indent.Open(); err != nil {
			return
		}
		if n.Prefix == "" {
			_, err = io.WriteString(w, "<"+n.Data)
		} else {
			_, err = fmt.Fprintf(w, "<%s:%s", n.Prefix, n.Data)
		}
		if err != nil {
			return
		}
	}

	for _, attr := range n.Attr {
		if attr.Name.Space != "" {
			_, err = fmt.Fprintf(w, ` %s:%s=`, attr.Name.Space, attr.Name.Local)
		} else {
			_, err = fmt.Fprintf(w, ` %s=`, attr.Name.Local)
		}
		if err != nil {
			return
		}

		_, err = fmt.Fprintf(w, `"%v"`, html.EscapeString(attr.Value))
		if err != nil {
			return
		}
	}
	if n.Type == DeclarationNode {
		_, err = io.WriteString(w, "?>")
	} else {
		if n.FirstChild != nil || !config.emptyElementTagSupport {
			_, err = io.WriteString(w, ">")
		} else {
			_, err = io.WriteString(w, "/>")
			if err != nil {
				return
			}
			err = indent.Close()
			return
		}
	}
	if err != nil {
		return
	}
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		err = outputXML(w, child, preserveSpaces, config, indent)
		if err != nil {
			return
		}
	}
	if n.Type != DeclarationNode {
		if err = indent.Close(); err != nil {
			return
		}
		if n.Prefix == "" {
			_, err = fmt.Fprintf(w, "</%s>", n.Data)
		} else {
			_, err = fmt.Fprintf(w, "</%s:%s>", n.Prefix, n.Data)
		}
	}
	return
}

// OutputXML returns the text that including tags name.
func (n *Node) OutputXML(self bool) string {
	if self {
		return n.OutputXMLWithOptions(WithOutputSelf())
	}
	return n.OutputXMLWithOptions()
}

// OutputXMLWithOptions returns the text that including tags name.
func (n *Node) OutputXMLWithOptions(opts ...OutputOption) string {
	var b strings.Builder
	_ = n.WriteWithOptions(&b, opts...)
	return b.String()
}

// Write writes xml to given writer.
func (n *Node) Write(writer io.Writer, self bool) error {
	if self {
		return n.WriteWithOptions(writer, WithOutputSelf())
	}
	return n.WriteWithOptions(writer)
}

// WriteWithOptions writes xml with given options to given writer.
func (n *Node) WriteWithOptions(writer io.Writer, opts ...OutputOption) (err error) {
	config := &outputConfiguration{
		preserveSpaces: true,
	}
	// Set the options
	for _, opt := range opts {
		opt(config)
	}
	pastPreserveSpaces := config.preserveSpaces
	preserveSpaces := calculatePreserveSpaces(n, pastPreserveSpaces)
	b := bufio.NewWriter(writer)
	defer b.Flush()

	ident := newIndentation(config.useIndentation, b)
	if config.printSelf && n.Type != DocumentNode {
		err = outputXML(b, n, preserveSpaces, config, ident)
	} else {
		for n := n.FirstChild; n != nil; n = n.NextSibling {
			err = outputXML(b, n, preserveSpaces, config, ident)
			if err != nil {
				break
			}
		}
	}
	return
}

// AddAttr adds a new attribute specified by 'key' and 'val' to a node 'n'.
// Returns false if the attribute already exists.
func AddAttr(n *Node, key, val string) bool {
	if n.HasAttr(key) {
		return false
	}
	attr := Attr{
		Name:  newXMLName(key),
		Value: val,
	}
	n.Attr = append(n.Attr, attr)
	return true
}

// HasAttr determines if an attribute exists.
func (n *Node) HasAttr(key string) bool {
	name := newXMLName(key)
	for _, attr := range n.Attr {
		if attr.Name == name {
			return true
		}
	}
	return false
}

// SetAttr allows an attribute value with the specified name to be changed.
// If the attribute did not previously exist, it will be created.
func (n *Node) SetAttr(key, value string) bool {
	name := newXMLName(key)
	for i, attr := range n.Attr {
		if attr.Name == name {
			n.Attr[i].Value = value
			return true
		}
	}
	return AddAttr(n, key, value)
}

// RemoveAttr removes the attribute with the specified name.
func (n *Node) RemoveAttr(key string) bool {
	name := newXMLName(key)
	for i, attr := range n.Attr {
		if attr.Name == name {
			n.Attr = append(n.Attr[:i], n.Attr[i+1:]...)
			return true
		}
	}
	return false
}

// AddChild adds a new node 'n' to a node 'parent' as its last child.
func AddChild(parent, n *Node) {
	n.Parent = parent
	n.NextSibling = nil
	if parent.FirstChild == nil {
		parent.FirstChild = n
		n.PrevSibling = nil
	} else {
		parent.LastChild.NextSibling = n
		n.PrevSibling = parent.LastChild
	}

	parent.LastChild = n
}

// AddSibling adds a new node 'n' as a last node of sibling chain for a given node 'sibling'.
func AddSibling(sibling, n *Node) {
	for t := sibling.NextSibling; t != nil; t = t.NextSibling {
		sibling = t
	}
	n.Parent = sibling.Parent
	sibling.NextSibling = n
	n.PrevSibling = sibling
	n.NextSibling = nil
	if sibling.Parent != nil {
		sibling.Parent.LastChild = n
	}
}

// AddImmediateSibling adds a new node 'n' as immediate sibling a given node 'sibling'.
func AddImmediateSibling(sibling, n *Node) {
	n.Parent = sibling.Parent
	n.NextSibling = sibling.NextSibling
	sibling.NextSibling = n
	n.PrevSibling = sibling
	if n.NextSibling != nil {
		n.NextSibling.PrevSibling = n
	} else if n.Parent != nil {
		sibling.Parent.LastChild = n
	}
}

// RemoveFromTree removes a node and its subtree from the document
// tree it is in. If the node is the root of the tree, then it's no-op.
func RemoveFromTree(n *Node) {
	if n.Parent == nil {
		return
	}
	if n.Parent.FirstChild == n {
		if n.Parent.LastChild == n {
			n.Parent.FirstChild = nil
			n.Parent.LastChild = nil
		} else {
			n.Parent.FirstChild = n.NextSibling
			n.NextSibling.PrevSibling = nil
		}
	} else {
		if n.Parent.LastChild == n {
			n.Parent.LastChild = n.PrevSibling
			n.PrevSibling.NextSibling = nil
		} else {
			n.PrevSibling.NextSibling = n.NextSibling
			n.NextSibling.PrevSibling = n.PrevSibling
		}
	}
	n.Parent = nil
	n.PrevSibling = nil
	n.NextSibling = nil
}

// GetRoot returns a root of the tree where 'n' is a node.
func GetRoot(n *Node) *Node {
	if n == nil {
		return nil
	}
	root := n
	for root.Parent != nil {
		root = root.Parent
	}
	return root
}