-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathelement.go
More file actions
389 lines (349 loc) · 13.3 KB
/
Copy pathelement.go
File metadata and controls
389 lines (349 loc) · 13.3 KB
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
package helium
import (
"fmt"
"strings"
)
// Element represents an XML element node (libxml2: xmlNode with type XML_ELEMENT_NODE).
type Element struct {
node
// contentHasReference records that a reference (a character reference or a
// general-entity reference) appeared directly in this element's content. A
// reference is content per XML production [43], so an element declared EMPTY
// that contains one is invalid (VC: Element Valid, errata 2e E15a) even when
// the reference expands to nothing and leaves the element childless. It is set
// by the parser and read ONLY by element-content validity; it is invisible to
// serialization, C14N, XPath, and copy.
contentHasReference bool
}
func newElement(name string) *Element {
e := Element{}
e.name = name
e.etype = ElementNode
return &e
}
// AddChild adds a new child node to the end of the children nodes (libxml2: xmlAddChild).
func (n *Element) AddChild(cur Node) error {
return addChild(n, cur)
}
// AppendText appends text content to this node (libxml2: xmlNodeAddContent).
func (n *Element) AppendText(b []byte) error {
return appendText(n, b)
}
// AddSibling adds a new sibling to the end of the sibling nodes (libxml2: xmlAddSibling).
func (n *Element) AddSibling(cur Node) error {
return addSibling(n, cur)
}
// Replace swaps this element out of its parent, inserting nodes in its place
// (libxml2: xmlReplaceNode). It returns an error if any operand is nil.
func (n *Element) Replace(nodes ...Node) error {
return replaceNode(n, nodes...)
}
// SetTreeDoc sets the owning document of this element and of every node in its
// subtree (libxml2: xmlSetTreeDoc).
func (n *Element) SetTreeDoc(doc *Document) {
setTreeDoc(n, doc)
}
// SetAttribute creates or replaces the attribute named name, storing value
// verbatim as a literal text child WITHOUT parsing it for entity references
// (so "A&B" is stored as the four characters A&B, and "&" as the five
// characters &). This mirrors libxml2 xmlSetProp. An existing attribute
// with the same QName is replaced in place. An empty value creates a text
// child with empty content, distinguishing it from a boolean attribute (see
// SetBooleanAttribute) which has no children. The name must not contain a
// colon; use SetAttributeNS for namespaced attributes. To parse entity
// references in value into the attribute's child list, use SetParsedAttribute.
func (n *Element) SetAttribute(name, value string) error {
if strings.ContainsRune(name, ':') {
return fmt.Errorf("attribute name %q contains a colon: use SetAttributeNS with a local name and Namespace parameter", name)
}
attr := newAttribute(name, nil)
attr.doc = n.doc
t := newText([]byte(value))
t.doc = n.doc
setFirstChild(attr, t)
setLastChild(attr, t)
t.parent = attr
n.addProperty(attr)
return nil
}
// SetParsedAttribute creates or replaces the attribute named name, parsing
// value for entity references into the attribute's child node list (so
// "&" resolves to a single '&', and a malformed reference such as "A&B"
// is an error). This mirrors libxml2 xmlNewDocProp. Prefer SetAttribute,
// which stores value verbatim; this variant is for callers that genuinely
// need raw XML entity syntax in value expanded (e.g. a parser building the
// DOM from unresolved attribute text). An existing attribute with the same
// QName is replaced in place. The name must not contain a colon; use
// SetParsedAttributeNS for namespaced attributes.
func (n *Element) SetParsedAttribute(name, value string) error {
attr, err := n.doc.CreateAttribute(name, value, nil)
if err != nil {
return err
}
n.addProperty(attr)
return nil
}
// SetBooleanAttribute creates a boolean attribute (name only, no value).
// The attribute has no children, distinguishing it from an attribute with
// an empty string value.
func (n *Element) SetBooleanAttribute(name string) error {
if strings.ContainsRune(name, ':') {
return fmt.Errorf("attribute name %q contains a colon", name)
}
attr := newAttribute(name, nil)
attr.doc = n.doc
n.addProperty(attr)
return nil
}
// attrMatches reports whether existing and the attribute identified by
// (qname, nsURI, localName) are the same attribute for the purposes of
// duplicate detection. Two attributes collide when EITHER their expanded
// name (namespace URI + local name) matches OR their serialized QName
// matches. The expanded-name test catches duplicates declared through
// different namespace prefixes that resolve to the same URI (e.g. p:a and
// q:a both bound to {urn:x}a); the QName test catches duplicates among
// no-namespace attributes and any other identical serialization.
//
// This is the single attribute-identity check used by addProperty, which
// backs every attribute-creation entry point (SetAttribute, SetAttributeNS,
// SetParsedAttribute, and SetParsedAttributeNS). A matching attribute is
// replaced in place; a new one is appended.
func attrMatches(existing *Attribute, qname, nsURI, localName string) bool {
if existing.URI() == nsURI && existing.LocalName() == localName {
return true
}
return existing.Name() == qname
}
// addProperty inserts or replaces an attribute in the element's property list.
func (n *Element) addProperty(attr *Attribute) {
p := n.properties
if p == nil {
n.properties = attr
attr.parent = n
return
}
qname := attr.Name()
nsURI := attr.URI()
localName := attr.LocalName()
var last *Attribute
for ; p != nil; p = p.NextAttribute() {
if attrMatches(p, qname, nsURI, localName) {
// Replace existing attribute in-place: splice new attr
// into the same position in the linked list.
pdn := p.baseDocNode()
attr.prev = pdn.prev
attr.next = pdn.next
attr.parent = n
if prev := pdn.prev; prev != nil {
prev.baseDocNode().next = attr
}
if next := pdn.next; next != nil {
next.baseDocNode().prev = attr
}
if n.properties == p {
n.properties = attr
}
// Detach old attribute
pdn.parent = nil
pdn.prev = nil
pdn.next = nil
return
}
last = p
}
last.next = attr
attr.prev = last
attr.parent = n
}
// SetAttributeNS creates or replaces the attribute with the given local name
// and namespace, storing value verbatim as a literal text child WITHOUT
// parsing it for entity references. This is the namespaced analogue of
// SetAttribute and mirrors libxml2 xmlSetProp. An existing attribute with the
// same expanded name (namespace URI + local name) or serialized QName is
// replaced in place. The local name must not contain a colon. To parse entity
// references in value into the attribute's child list, use
// SetParsedAttributeNS.
func (n *Element) SetAttributeNS(localname, value string, ns *Namespace) error {
if strings.ContainsRune(localname, ':') {
return fmt.Errorf("attribute local name %q contains a colon", localname)
}
attr := newAttribute(localname, ns)
attr.doc = n.doc
t := newText([]byte(value))
t.doc = n.doc
setFirstChild(attr, t)
setLastChild(attr, t)
t.parent = attr
n.addProperty(attr)
return nil
}
// SetParsedAttributeNS creates or replaces the attribute with the given local
// name and namespace, parsing value for entity references into the attribute's
// child node list. This is the namespaced analogue of SetParsedAttribute and
// mirrors libxml2 xmlNewDocProp. Prefer SetAttributeNS, which stores value
// verbatim; this variant is for callers that genuinely need raw XML entity
// syntax in value expanded. An existing attribute with the same expanded name
// (namespace URI + local name) or serialized QName is replaced in place. The
// local name must not contain a colon.
func (n *Element) SetParsedAttributeNS(localname, value string, ns *Namespace) error {
attr, err := n.doc.CreateAttribute(localname, value, ns)
if err != nil {
return err
}
n.addProperty(attr)
return nil
}
// AttributePredicate reports whether an attribute matches a lookup.
// Implementations are used by FindAttribute to support alternate
// matching semantics without exposing the property list layout.
type AttributePredicate interface {
Match(*Attribute) bool
}
// QNamePredicate matches an attribute by QName as returned by Attribute.Name.
type QNamePredicate string
func (p QNamePredicate) Match(a *Attribute) bool {
return a.Name() == string(p)
}
// LocalNamePredicate matches an attribute by local name only.
// If multiple attributes share the same local name, FindAttribute returns
// the first match in property order.
type LocalNamePredicate string
func (p LocalNamePredicate) Match(a *Attribute) bool {
return a.LocalName() == string(p)
}
// NSPredicate matches an attribute by local name + namespace URI.
type NSPredicate struct {
Local string
NamespaceURI string
}
func (p NSPredicate) Match(a *Attribute) bool {
return a.LocalName() == p.Local && a.URI() == p.NamespaceURI
}
// FindAttribute returns the first attribute that matches ap in property order.
// A nil predicate matches nothing and returns nil, false.
func (n *Element) FindAttribute(ap AttributePredicate) (*Attribute, bool) {
if ap == nil {
return nil, false
}
for p := n.properties; p != nil; p = p.NextAttribute() {
if ap.Match(p) {
return p, true
}
}
return nil, false
}
// GetAttribute returns the value of the attribute with the given QName,
// or empty string and false if not found.
func (n *Element) GetAttribute(name string) (string, bool) {
attr, ok := n.FindAttribute(QNamePredicate(name))
if !ok {
return "", false
}
return attr.Value(), true
}
// HasAttribute reports whether the element has an attribute with the given name.
func (n *Element) HasAttribute(name string) bool {
_, ok := n.FindAttribute(QNamePredicate(name))
return ok
}
// GetAttributeNS returns the value of the attribute with the given
// local name and namespace URI, or empty string and false if not found.
func (n *Element) GetAttributeNS(localName, nsURI string) (string, bool) {
attr, ok := n.FindAttribute(NSPredicate{Local: localName, NamespaceURI: nsURI})
if !ok {
return "", false
}
return attr.Value(), true
}
// GetAttributeNodeNS returns the Attribute node with the given local name and
// namespace URI, or nil if not found. This is the equivalent of libxml2's
// xmlHasNsProp, returning the node itself for further inspection (e.g.,
// checking atype or whether it is a default attribute).
func (n *Element) GetAttributeNodeNS(localName, nsURI string) *Attribute {
attr, ok := n.FindAttribute(NSPredicate{Local: localName, NamespaceURI: nsURI})
if !ok {
return nil
}
return attr
}
// RemoveAttribute removes the attribute with the given QName from the element.
// Returns true if an attribute was removed.
func (n *Element) RemoveAttribute(name string) bool {
attr, ok := n.FindAttribute(QNamePredicate(name))
if !ok {
return false
}
n.spliceOutAttribute(attr)
return true
}
// RemoveAttributeNS removes the attribute with the given local name and
// namespace URI. Returns true if an attribute was removed.
func (n *Element) RemoveAttributeNS(localName, nsURI string) bool {
attr, ok := n.FindAttribute(NSPredicate{Local: localName, NamespaceURI: nsURI})
if !ok {
return false
}
n.spliceOutAttribute(attr)
return true
}
// hasAttributeInProperties reports whether p is reachable from this element's
// properties linked list by identity. An *Attribute whose parent is an *Element
// is not guaranteed to live in that element's properties chain: a generic
// Replace(attr) that swaps a child node for an attribute places the attribute in
// the normal child list instead (elem.AddChild(attr) always routes into the
// properties list, so it never produces such a case). Property-list splicing must
// only be used when the attribute is genuinely a property; otherwise
// firstChild/lastChild would be left stale.
func (n *Element) hasAttributeInProperties(p *Attribute) bool {
for attr := n.properties; attr != nil; attr = attr.NextAttribute() {
if attr == p {
return true
}
}
return false
}
// spliceOutAttribute removes an attribute from the element's property linked list.
func (n *Element) spliceOutAttribute(p *Attribute) {
pdn := p.baseDocNode()
if prev := pdn.prev; prev != nil {
prev.baseDocNode().next = pdn.next
}
if next := pdn.next; next != nil {
next.baseDocNode().prev = pdn.prev
}
if n.properties == p {
n.properties = p.NextAttribute()
}
pdn.parent = nil
pdn.prev = nil
pdn.next = nil
}
// Attributes returns a newly allocated slice of the element's attributes in
// property order. The returned slice is a snapshot: appending to or reordering
// it does not affect the element, though the *Attribute elements still point at
// the live attribute nodes. Use ForEachAttribute to avoid the slice allocation.
func (n *Element) Attributes() []*Attribute {
attrs := []*Attribute{}
for attr := n.properties; attr != nil; attr = attr.NextAttribute() {
attrs = append(attrs, attr)
}
return attrs
}
// ForEachAttribute calls fn for each attribute on the element.
// If fn returns false, iteration stops early.
// This avoids the slice allocation of Attributes().
//
// attr_test.go covers both full iteration and the early-stop path; the
// nine production call sites all return true, so attr_test.go is the
// early-stop path's only exercise.
//
// The loop walks the properties chain via NextAttribute() and asserts
// nothing: the chain is attribute-only by construction (field typed
// *Attribute, only *Attribute nodes are ever linked in).
func (n *Element) ForEachAttribute(fn func(*Attribute) bool) {
for attr := n.properties; attr != nil; attr = attr.NextAttribute() {
if !fn(attr) {
return
}
}
}