Debian Codegraph @

etree.go

raw symbols SCIP
1 // Copyright 2015-2019 Brett Vickers.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package etree provides XML services through an Element Tree
6 // abstraction.
7 package etree
8
9 import (
10 "bufio"
11 "bytes"
12 "encoding/xml"
13 "errors"
14 "io"
15 "iter"
16 "maps"
17 "os"
18 "slices"
19 "strings"
20 )
21
22 const (
23 // NoIndent is used with the IndentSettings record to remove all
24 // indenting.
25 NoIndent = -1
26 )
27
28 // ErrXML is returned when XML parsing fails due to incorrect formatting.
29 var ErrXML = errors.New("etree: invalid XML format")
30
31 // ErrMaxDepth is returned when the depth of the XML tree being read exceeds
32 // the maximum depth allowed by ReadSettings.MaxDepth.
33 var ErrMaxDepth = errors.New("etree: XML tree exceeds maximum depth")
34
35 // cdataPrefix is used to detect CDATA text when ReadSettings.PreserveCData is
36 // true.
37 var cdataPrefix = []byte("<![CDATA[")
38
39 // ReadSettings determine the default behavior of the Document's ReadFrom*
40 // functions.
41 type ReadSettings struct {
42 // CharsetReader, if non-nil, defines a function to generate
43 // charset-conversion readers, converting from the provided non-UTF-8
44 // charset into UTF-8. If nil, the ReadFrom* functions will use a
45 // "pass-through" CharsetReader that performs no conversion on the reader's
46 // data regardless of the value of the "charset" encoding string. Default:
47 // nil.
48 CharsetReader func(charset string, input io.Reader) (io.Reader, error)
49
50 // Permissive allows input containing common mistakes such as missing tags
51 // or attribute values. Default: false.
52 Permissive bool
53
54 // Preserve CDATA character data blocks when decoding XML (instead of
55 // converting it to normal character text). This entails additional
56 // processing and memory usage during ReadFrom* operations. Default:
57 // false.
58 PreserveCData bool
59
60 // When an element has two or more attributes with the same name,
61 // preserve them instead of keeping only one. Default: false.
62 PreserveDuplicateAttrs bool
63
64 // ValidateInput forces all ReadFrom* functions to validate that the
65 // provided input is composed of "well-formed"(*) XML before processing it.
66 // If invalid XML is detected, the ReadFrom* functions return an error.
67 // Because this option requires the input to be processed twice, it incurs a
68 // significant performance penalty. Default: false.
69 //
70 // (*) Note that this definition of "well-formed" is in the context of the
71 // go standard library's encoding/xml package. Go's encoding/xml package
72 // does not, in fact, guarantee well-formed XML as specified by the W3C XML
73 // recommendation. See: https://github.com/golang/go/issues/68299
74 ValidateInput bool
75
76 // Entity to be passed to standard xml.Decoder. Default: nil.
77 Entity map[string]string
78
79 // When Permissive is true, AutoClose indicates a set of elements to
80 // consider closed immediately after they are opened, regardless of
81 // whether an end element is present. Commonly set to xml.HTMLAutoClose.
82 // Default: nil.
83 AutoClose []string
84
85 // MaxDepth is the maximum depth of the XML tree to parse. If the depth of
86 // the XML tree exceeds this value, all ReadFrom* functions return the
87 // error ErrMaxDepth. If MaxDepth is zero or negative, a depth limit of
88 // 1024 is used. Default: 0 (i.e., a limit of 1024).
89 MaxDepth int
90 }
91
92 // defaultMaxDepth is the maximum depth of an XML tree parsed by ReadFrom*
93 // functions when ReadSettings.MaxDepth is not set to a positive value.
94 const defaultMaxDepth = 1024
95
96 // defaultCharsetReader is used by the xml decoder when the ReadSettings
97 // CharsetReader value is nil. It behaves as a "pass-through", ignoring
98 // the requested charset parameter and skipping conversion altogether.
99 func defaultCharsetReader(charset string, input io.Reader) (io.Reader, error) {
100 return input, nil
101 }
102
103 // dup creates a duplicate of the ReadSettings object.
104 func (s *ReadSettings) dup() ReadSettings {
105 c := *s
106 c.Entity = maps.Clone(s.Entity)
107 return c
108 }
109
110 // WriteSettings determine the behavior of the Document's WriteTo* functions.
111 type WriteSettings struct {
112 // CanonicalEndTags forces the production of XML end tags, even for
113 // elements that have no child elements. Default: false.
114 CanonicalEndTags bool
115
116 // CanonicalText forces the production of XML character references for
117 // text data characters &, <, and >. If false, XML character references
118 // are also produced for " and '. Default: false.
119 CanonicalText bool
120
121 // CanonicalAttrVal forces the production of XML character references for
122 // attribute value characters &, < and ". If false, XML character
123 // references are also produced for > and '. Ignored when AttrSingleQuote
124 // is true. Default: false.
125 CanonicalAttrVal bool
126
127 // AttrSingleQuote causes attributes to use single quotes (attr='example')
128 // instead of double quotes (attr = "example") when set to true. Default:
129 // false.
130 AttrSingleQuote bool
131
132 // UseCRLF causes the document's Indent* functions to use a carriage return
133 // followed by a linefeed ("\r\n") when outputting a newline. If false,
134 // only a linefeed is used ("\n"). Default: false.
135 //
136 // Deprecated: UseCRLF is deprecated. Use IndentSettings.UseCRLF instead.
137 UseCRLF bool
138 }
139
140 // dup creates a duplicate of the WriteSettings object.
141 func (s *WriteSettings) dup() WriteSettings {
142 return *s
143 }
144
145 // IndentSettings determine the behavior of the Document's Indent* functions.
146 type IndentSettings struct {
147 // Spaces indicates the number of spaces to insert for each level of
148 // indentation. Set to etree.NoIndent to remove all indentation. Ignored
149 // when UseTabs is true. Default: 4.
150 Spaces int
151
152 // UseTabs causes tabs to be used instead of spaces when indenting.
153 // Default: false.
154 UseTabs bool
155
156 // UseCRLF causes newlines to be written as a carriage return followed by
157 // a linefeed ("\r\n"). If false, only a linefeed character is output
158 // for a newline ("\n"). Default: false.
159 UseCRLF bool
160
161 // PreserveLeafWhitespace causes indent functions to preserve whitespace
162 // within XML elements containing only non-CDATA character data. Default:
163 // false.
164 PreserveLeafWhitespace bool
165
166 // SuppressTrailingWhitespace suppresses the generation of a trailing
167 // whitespace characters (such as newlines) at the end of the indented
168 // document. Default: false.
169 SuppressTrailingWhitespace bool
170 }
171
172 // NewIndentSettings creates a default IndentSettings record.
173 func NewIndentSettings() *IndentSettings {
174 return &IndentSettings{
175 Spaces: 4,
176 UseTabs: false,
177 UseCRLF: false,
178 PreserveLeafWhitespace: false,
179 SuppressTrailingWhitespace: false,
180 }
181 }
182
183 type indentFunc func(depth int) string
184
185 func getIndentFunc(s *IndentSettings) indentFunc {
186 if s.UseTabs {
187 if s.UseCRLF {
188 return func(depth int) string { return indentCRLF(depth, indentTabs) }
189 } else {
190 return func(depth int) string { return indentLF(depth, indentTabs) }
191 }
192 } else {
193 if s.Spaces < 0 {
194 return func(depth int) string { return "" }
195 } else if s.UseCRLF {
196 return func(depth int) string { return indentCRLF(depth*s.Spaces, indentSpaces) }
197 } else {
198 return func(depth int) string { return indentLF(depth*s.Spaces, indentSpaces) }
199 }
200 }
201 }
202
203 // Writer is the interface that wraps the Write* functions called by each token
204 // type's WriteTo function.
205 type Writer interface {
206 io.StringWriter
207 io.ByteWriter
208 io.Writer
209 }
210
211 // A Token is an interface type used to represent XML elements, character
212 // data, CDATA sections, XML comments, XML directives, and XML processing
213 // instructions.
214 type Token interface {
215 Parent() *Element
216 Index() int
217 WriteTo(w Writer, s *WriteSettings)
218 dup(parent *Element) Token
219 setParent(parent *Element)
220 setIndex(index int)
221 }
222
223 // A Document is a container holding a complete XML tree.
224 //
225 // A document has a single embedded element, which contains zero or more child
226 // tokens, one of which is usually the root element. The embedded element may
227 // include other children such as processing instruction tokens or character
228 // data tokens. The document's embedded element is never directly serialized;
229 // only its children are.
230 //
231 // A document also contains read and write settings, which influence the way
232 // the document is deserialized, serialized, and indented.
233 type Document struct {
234 Element
235 ReadSettings ReadSettings
236 WriteSettings WriteSettings
237 }
238
239 // An Element represents an XML element, its attributes, and its child tokens.
240 type Element struct {
241 Space, Tag string // namespace prefix and tag
242 Attr []Attr // key-value attribute pairs
243 Child []Token // child tokens (elements, comments, etc.)
244 parent *Element // parent element
245 index int // token index in parent's children
246 }
247
248 // An Attr represents a key-value attribute within an XML element.
249 type Attr struct {
250 Space, Key string // The attribute's namespace prefix and key
251 Value string // The attribute value string
252 element *Element // element containing the attribute
253 }
254
255 // charDataFlags are used with CharData tokens to store additional settings.
256 type charDataFlags uint8
257
258 const (
259 // The CharData contains only whitespace.
260 whitespaceFlag charDataFlags = 1 << iota
261
262 // The CharData contains a CDATA section.
263 cdataFlag
264 )
265
266 // CharData may be used to represent simple text data or a CDATA section
267 // within an XML document. The Data property should never be modified
268 // directly; use the SetData function instead.
269 type CharData struct {
270 Data string // the simple text or CDATA section content
271 parent *Element
272 index int
273 flags charDataFlags
274 }
275
276 // A Comment represents an XML comment.
277 type Comment struct {
278 Data string // the comment's text
279 parent *Element
280 index int
281 }
282
283 // A Directive represents an XML directive.
284 type Directive struct {
285 Data string // the directive string
286 parent *Element
287 index int
288 }
289
290 // A ProcInst represents an XML processing instruction.
291 type ProcInst struct {
292 Target string // the processing instruction target
293 Inst string // the processing instruction value
294 parent *Element
295 index int
296 }
297
298 // NewDocument creates an XML document without a root element.
299 func NewDocument() *Document {
300 return &Document{
301 Element: Element{Child: make([]Token, 0)},
302 }
303 }
304
305 // NewDocumentWithRoot creates an XML document and sets the element 'e' as its
306 // root element. If the element 'e' is already part of another document, it is
307 // first removed from its existing document.
308 func NewDocumentWithRoot(e *Element) *Document {
309 d := NewDocument()
310 d.SetRoot(e)
311 return d
312 }
313
314 // Copy returns a recursive, deep copy of the document.
315 func (d *Document) Copy() *Document {
316 return &Document{
317 Element: *(d.Element.dup(nil).(*Element)),
318 ReadSettings: d.ReadSettings.dup(),
319 WriteSettings: d.WriteSettings.dup(),
320 }
321 }
322
323 // Root returns the root element of the document. It returns nil if there is
324 // no root element.
325 func (d *Document) Root() *Element {
326 for _, t := range d.Child {
327 if c, ok := t.(*Element); ok {
328 return c
329 }
330 }
331 return nil
332 }
333
334 // SetRoot replaces the document's root element with the element 'e'. If the
335 // document already has a root element when this function is called, then the
336 // existing root element is unbound from the document. If the element 'e' is
337 // part of another document, then it is unbound from the other document.
338 func (d *Document) SetRoot(e *Element) {
339 if e.parent != nil {
340 e.parent.RemoveChild(e)
341 }
342
343 // If there is already a root element, replace it.
344 p := &d.Element
345 for i, t := range p.Child {
346 if _, ok := t.(*Element); ok {
347 t.setParent(nil)
348 t.setIndex(-1)
349 p.Child[i] = e
350 e.setParent(p)
351 e.setIndex(i)
352 return
353 }
354 }
355
356 // No existing root element, so add it.
357 p.addChild(e)
358 }
359
360 // ReadFrom reads XML from the reader 'r' into this document. The function
361 // returns the number of bytes read and any error encountered.
362 func (d *Document) ReadFrom(r io.Reader) (n int64, err error) {
363 if d.ReadSettings.ValidateInput {
364 b, err := io.ReadAll(r)
365 if err != nil {
366 return 0, err
367 }
368 if err := validateXML(bytes.NewReader(b), d.ReadSettings); err != nil {
369 return 0, err
370 }
371 r = bytes.NewReader(b)
372 }
373 return d.Element.readFrom(r, d.ReadSettings)
374 }
375
376 // ReadFromFile reads XML from a local file at path 'filepath' into this
377 // document.
378 func (d *Document) ReadFromFile(filepath string) error {
379 f, err := os.Open(filepath)
380 if err != nil {
381 return err
382 }
383 defer f.Close()
384
385 _, err = d.ReadFrom(f)
386 return err
387 }
388
389 // ReadFromBytes reads XML from the byte slice 'b' into the this document.
390 func (d *Document) ReadFromBytes(b []byte) error {
391 if d.ReadSettings.ValidateInput {
392 if err := validateXML(bytes.NewReader(b), d.ReadSettings); err != nil {
393 return err
394 }
395 }
396 _, err := d.Element.readFrom(bytes.NewReader(b), d.ReadSettings)
397 return err
398 }
399
400 // ReadFromString reads XML from the string 's' into this document.
401 func (d *Document) ReadFromString(s string) error {
402 if d.ReadSettings.ValidateInput {
403 if err := validateXML(strings.NewReader(s), d.ReadSettings); err != nil {
404 return err
405 }
406 }
407 _, err := d.Element.readFrom(strings.NewReader(s), d.ReadSettings)
408 return err
409 }
410
411 // validateXML determines if the data read from the reader 'r' contains
412 // well-formed XML according to the rules set by the go xml package.
413 func validateXML(r io.Reader, settings ReadSettings) error {
414 dec := newDecoder(r, settings)
415 err := dec.Decode(new(interface{}))
416 if err != nil {
417 return err
418 }
419
420 // If there are any trailing tokens after unmarshalling with Decode(),
421 // then the XML input didn't terminate properly.
422 _, err = dec.Token()
423 if err == io.EOF {
424 return nil
425 }
426 return ErrXML
427 }
428
429 // newDecoder creates an XML decoder for the reader 'r' configured using
430 // the provided read settings.
431 func newDecoder(r io.Reader, settings ReadSettings) *xml.Decoder {
432 d := xml.NewDecoder(r)
433 d.CharsetReader = settings.CharsetReader
434 if d.CharsetReader == nil {
435 d.CharsetReader = defaultCharsetReader
436 }
437 d.Strict = !settings.Permissive
438 d.Entity = settings.Entity
439 d.AutoClose = settings.AutoClose
440 return d
441 }
442
443 // WriteTo serializes the document out to the writer 'w'. The function returns
444 // the number of bytes written and any error encountered.
445 func (d *Document) WriteTo(w io.Writer) (n int64, err error) {
446 xw := newXmlWriter(w)
447 b := bufio.NewWriter(xw)
448 for _, c := range d.Child {
449 c.WriteTo(b, &d.WriteSettings)
450 }
451 err, n = b.Flush(), xw.bytes
452 return
453 }
454
455 // WriteToFile serializes the document out to the file at path 'filepath'.
456 func (d *Document) WriteToFile(filepath string) error {
457 f, err := os.Create(filepath)
458 if err != nil {
459 return err
460 }
461 defer f.Close()
462 _, err = d.WriteTo(f)
463 return err
464 }
465
466 // WriteToBytes serializes this document into a slice of bytes.
467 func (d *Document) WriteToBytes() (b []byte, err error) {
468 var buf bytes.Buffer
469 if _, err = d.WriteTo(&buf); err != nil {
470 return
471 }
472 return buf.Bytes(), nil
473 }
474
475 // WriteToString serializes this document into a string.
476 func (d *Document) WriteToString() (s string, err error) {
477 var b []byte
478 if b, err = d.WriteToBytes(); err != nil {
479 return
480 }
481 return string(b), nil
482 }
483
484 // Indent modifies the document's element tree by inserting character data
485 // tokens containing newlines and spaces for indentation. The amount of
486 // indentation per depth level is given by the 'spaces' parameter. Other than
487 // the number of spaces, default IndentSettings are used.
488 func (d *Document) Indent(spaces int) {
489 s := NewIndentSettings()
490 s.Spaces = spaces
491 d.IndentWithSettings(s)
492 }
493
494 // IndentTabs modifies the document's element tree by inserting CharData
495 // tokens containing newlines and tabs for indentation. One tab is used per
496 // indentation level. Other than the use of tabs, default IndentSettings
497 // are used.
498 func (d *Document) IndentTabs() {
499 s := NewIndentSettings()
500 s.UseTabs = true
501 d.IndentWithSettings(s)
502 }
503
504 // IndentWithSettings modifies the document's element tree by inserting
505 // character data tokens containing newlines and indentation. The behavior
506 // of the indentation algorithm is configured by the indent settings.
507 func (d *Document) IndentWithSettings(s *IndentSettings) {
508 // WriteSettings.UseCRLF is deprecated. Until removed from the package, it
509 // overrides IndentSettings.UseCRLF when true.
510 if d.WriteSettings.UseCRLF {
511 s.UseCRLF = true
512 }
513
514 d.Element.indent(0, getIndentFunc(s), s)
515
516 if s.SuppressTrailingWhitespace {
517 d.Element.stripTrailingWhitespace()
518 }
519 }
520
521 // Unindent modifies the document's element tree by removing character data
522 // tokens containing only whitespace. Other than the removal of indentation,
523 // default IndentSettings are used.
524 func (d *Document) Unindent() {
525 s := NewIndentSettings()
526 s.Spaces = NoIndent
527 d.IndentWithSettings(s)
528 }
529
530 // NewElement creates an unparented element with the specified tag (i.e.,
531 // name). The tag may include a namespace prefix followed by a colon.
532 func NewElement(tag string) *Element {
533 space, stag := spaceDecompose(tag)
534 return newElement(space, stag, nil)
535 }
536
537 // newElement is a helper function that creates an element and binds it to
538 // a parent element if possible.
539 func newElement(space, tag string, parent *Element) *Element {
540 e := &Element{
541 Space: space,
542 Tag: tag,
543 Attr: make([]Attr, 0),
544 Child: make([]Token, 0),
545 parent: parent,
546 index: -1,
547 }
548 if parent != nil {
549 parent.addChild(e)
550 }
551 return e
552 }
553
554 // Copy creates a recursive, deep copy of the element and all its attributes
555 // and children. The returned element has no parent but can be parented to a
556 // another element using AddChild, or added to a document with SetRoot or
557 // NewDocumentWithRoot.
558 func (e *Element) Copy() *Element {
559 return e.dup(nil).(*Element)
560 }
561
562 // FullTag returns the element e's complete tag, including namespace prefix if
563 // present.
564 func (e *Element) FullTag() string {
565 if e.Space == "" {
566 return e.Tag
567 }
568 return e.Space + ":" + e.Tag
569 }
570
571 // NamespaceURI returns the XML namespace URI associated with the element. If
572 // the element is part of the XML default namespace, NamespaceURI returns the
573 // empty string.
574 func (e *Element) NamespaceURI() string {
575 if e.Space == "" {
576 return e.findDefaultNamespaceURI()
577 }
578 return e.findLocalNamespaceURI(e.Space)
579 }
580
581 // findLocalNamespaceURI finds the namespace URI corresponding to the
582 // requested prefix.
583 func (e *Element) findLocalNamespaceURI(prefix string) string {
584 for _, a := range e.Attr {
585 if a.Space == "xmlns" && a.Key == prefix {
586 return a.Value
587 }
588 }
589
590 if e.parent == nil {
591 return ""
592 }
593
594 return e.parent.findLocalNamespaceURI(prefix)
595 }
596
597 // findDefaultNamespaceURI finds the default namespace URI of the element.
598 func (e *Element) findDefaultNamespaceURI() string {
599 for _, a := range e.Attr {
600 if a.Space == "" && a.Key == "xmlns" {
601 return a.Value
602 }
603 }
604
605 if e.parent == nil {
606 return ""
607 }
608
609 return e.parent.findDefaultNamespaceURI()
610 }
611
612 // namespacePrefix returns the namespace prefix associated with the element.
613 func (e *Element) namespacePrefix() string {
614 return e.Space
615 }
616
617 // name returns the tag associated with the element.
618 func (e *Element) name() string {
619 return e.Tag
620 }
621
622 // ReindexChildren recalculates the index values of the element's child
623 // tokens. This is necessary only if you have manually manipulated the
624 // element's `Child` array.
625 func (e *Element) ReindexChildren() {
626 for i := 0; i < len(e.Child); i++ {
627 e.Child[i].setIndex(i)
628 }
629 }
630
631 // Text returns all character data immediately following the element's opening
632 // tag.
633 func (e *Element) Text() string {
634 if len(e.Child) == 0 {
635 return ""
636 }
637
638 var text string
639 var b strings.Builder
640 for _, ch := range e.Child {
641 if cd, ok := ch.(*CharData); ok {
642 if text == "" {
643 text = cd.Data
644 } else {
645 if b.Len() == 0 {
646 b.WriteString(text)
647 }
648 b.WriteString(cd.Data)
649 }
650 } else if _, ok := ch.(*Comment); ok {
651 // ignore
652 } else {
653 break
654 }
655 }
656
657 if b.Len() > 0 {
658 return b.String()
659 }
660 return text
661 }
662
663 // SetText replaces all character data immediately following an element's
664 // opening tag with the requested string.
665 func (e *Element) SetText(text string) {
666 e.replaceText(0, text, 0)
667 }
668
669 // SetCData replaces all character data immediately following an element's
670 // opening tag with a CDATA section.
671 func (e *Element) SetCData(text string) {
672 e.replaceText(0, text, cdataFlag)
673 }
674
675 // Tail returns all character data immediately following the element's end
676 // tag.
677 func (e *Element) Tail() string {
678 if e.Parent() == nil {
679 return ""
680 }
681
682 p := e.Parent()
683 i := e.Index()
684
685 var text string
686 var b strings.Builder
687 for _, ch := range p.Child[i+1:] {
688 if cd, ok := ch.(*CharData); ok {
689 if text == "" {
690 text = cd.Data
691 } else {
692 if b.Len() == 0 {
693 b.WriteString(text)
694 }
695 b.WriteString(cd.Data)
696 }
697 } else {
698 break
699 }
700 }
701
702 if b.Len() > 0 {
703 return b.String()
704 }
705 return text
706 }
707
708 // SetTail replaces all character data immediately following the element's end
709 // tag with the requested string.
710 func (e *Element) SetTail(text string) {
711 if e.Parent() == nil {
712 return
713 }
714
715 p := e.Parent()
716 p.replaceText(e.Index()+1, text, 0)
717 }
718
719 // replaceText is a helper function that replaces a series of chardata tokens
720 // starting at index i with the requested text.
721 func (e *Element) replaceText(i int, text string, flags charDataFlags) {
722 end := e.findTermCharDataIndex(i)
723
724 switch {
725 case end == i:
726 if text != "" {
727 // insert a new chardata token at index i
728 cd := newCharData(text, flags, nil)
729 e.InsertChildAt(i, cd)
730 }
731
732 case end == i+1:
733 if text == "" {
734 // remove the chardata token at index i
735 e.RemoveChildAt(i)
736 } else {
737 // replace the first and only character token at index i
738 cd := e.Child[i].(*CharData)
739 cd.Data, cd.flags = text, flags
740 }
741
742 default:
743 if text == "" {
744 // remove all chardata tokens starting from index i
745 copy(e.Child[i:], e.Child[end:])
746 removed := end - i
747 e.Child = e.Child[:len(e.Child)-removed]
748 for j := i; j < len(e.Child); j++ {
749 e.Child[j].setIndex(j)
750 }
751 } else {
752 // replace the first chardata token at index i and remove all
753 // subsequent chardata tokens
754 cd := e.Child[i].(*CharData)
755 cd.Data, cd.flags = text, flags
756 copy(e.Child[i+1:], e.Child[end:])
757 removed := end - (i + 1)
758 e.Child = e.Child[:len(e.Child)-removed]
759 for j := i + 1; j < len(e.Child); j++ {
760 e.Child[j].setIndex(j)
761 }
762 }
763 }
764 }
765
766 // findTermCharDataIndex finds the index of the first child token that isn't
767 // a CharData token. It starts from the requested start index.
768 func (e *Element) findTermCharDataIndex(start int) int {
769 for i := start; i < len(e.Child); i++ {
770 if _, ok := e.Child[i].(*CharData); !ok {
771 return i
772 }
773 }
774 return len(e.Child)
775 }
776
777 // CreateElement creates a new element with the specified tag (i.e., name) and
778 // adds it as the last child of element 'e'. The tag may include a prefix
779 // followed by a colon.
780 func (e *Element) CreateElement(tag string) *Element {
781 space, stag := spaceDecompose(tag)
782 return newElement(space, stag, e)
783 }
784
785 // CreateChild performs the same task as CreateElement but calls a
786 // continuation function after the child element is created, allowing
787 // additional actions to be performed on the child element before returning.
788 //
789 // This method of element creation is particularly useful when building nested
790 // XML documents from code. For example:
791 //
792 // org := doc.CreateChild("organization", func(e *Element) {
793 // e.CreateComment("Mary")
794 // e.CreateChild("person", func(e *Element) {
795 // e.CreateAttr("name", "Mary")
796 // e.CreateAttr("age", "30")
797 // e.CreateAttr("hair", "brown")
798 // })
799 // })
800 func (e *Element) CreateChild(tag string, cont func(e *Element)) *Element {
801 child := e.CreateElement(tag)
802 cont(child)
803 return child
804 }
805
806 // AddChild adds the token 't' as the last child of the element. If token 't'
807 // was already the child of another element, it is first removed from its
808 // parent element.
809 func (e *Element) AddChild(t Token) {
810 if t.Parent() != nil {
811 t.Parent().RemoveChild(t)
812 }
813 e.addChild(t)
814 }
815
816 // InsertChild inserts the token 't' into this element's list of children just
817 // before the element's existing child token 'ex'. If the existing element
818 // 'ex' does not appear in this element's list of child tokens, then 't' is
819 // added to the end of this element's list of child tokens. If token 't' is
820 // already the child of another element, it is first removed from the other
821 // element's list of child tokens.
822 //
823 // Deprecated: InsertChild is deprecated. Use InsertChildAt instead.
824 func (e *Element) InsertChild(ex Token, t Token) {
825 if ex == nil || ex.Parent() != e {
826 e.AddChild(t)
827 return
828 }
829
830 if t.Parent() != nil {
831 t.Parent().RemoveChild(t)
832 }
833
834 t.setParent(e)
835
836 i := ex.Index()
837 e.Child = append(e.Child, nil)
838 copy(e.Child[i+1:], e.Child[i:])
839 e.Child[i] = t
840
841 for j := i; j < len(e.Child); j++ {
842 e.Child[j].setIndex(j)
843 }
844 }
845
846 // InsertChildAt inserts the token 't' into this element's list of child
847 // tokens just before the requested 'index'. If the index is greater than or
848 // equal to the length of the list of child tokens, then the token 't' is
849 // added to the end of the list of child tokens.
850 func (e *Element) InsertChildAt(index int, t Token) {
851 if index >= len(e.Child) {
852 e.AddChild(t)
853 return
854 }
855
856 if t.Parent() != nil {
857 if t.Parent() == e && t.Index() < index {
858 index--
859 }
860 t.Parent().RemoveChild(t)
861 }
862
863 t.setParent(e)
864
865 e.Child = append(e.Child, nil)
866 copy(e.Child[index+1:], e.Child[index:])
867 e.Child[index] = t
868
869 for j := index; j < len(e.Child); j++ {
870 e.Child[j].setIndex(j)
871 }
872 }
873
874 // RemoveChild attempts to remove the token 't' from this element's list of
875 // child tokens. If the token 't' was a child of this element, then it is
876 // removed and returned. Otherwise, nil is returned.
877 func (e *Element) RemoveChild(t Token) Token {
878 if t.Parent() != e {
879 return nil
880 }
881 return e.RemoveChildAt(t.Index())
882 }
883
884 // RemoveChildAt removes the child token appearing in slot 'index' of this
885 // element's list of child tokens. The removed child token is then returned.
886 // If the index is out of bounds, no child is removed and nil is returned.
887 func (e *Element) RemoveChildAt(index int) Token {
888 if index >= len(e.Child) {
889 return nil
890 }
891
892 t := e.Child[index]
893 for j := index + 1; j < len(e.Child); j++ {
894 e.Child[j].setIndex(j - 1)
895 }
896 e.Child = append(e.Child[:index], e.Child[index+1:]...)
897 t.setIndex(-1)
898 t.setParent(nil)
899 return t
900 }
901
902 // autoClose analyzes the stack's top element and the current token to decide
903 // whether the top element should be closed.
904 func (e *Element) autoClose(stack *stack[*Element], t xml.Token, tags []string) {
905 if stack.empty() {
906 return
907 }
908
909 top := stack.peek()
910
911 for _, tag := range tags {
912 if strings.EqualFold(tag, top.FullTag()) {
913 if e, ok := t.(xml.EndElement); !ok ||
914 !strings.EqualFold(e.Name.Space, top.Space) ||
915 !strings.EqualFold(e.Name.Local, top.Tag) {
916 stack.pop()
917 }
918 break
919 }
920 }
921 }
922
923 // ReadFrom reads XML from the reader 'ri' and stores the result as a new
924 // child of this element.
925 func (e *Element) readFrom(ri io.Reader, settings ReadSettings) (n int64, err error) {
926 var r xmlReader
927 var pr *xmlPeekReader
928 if settings.PreserveCData {
929 pr = newXmlPeekReader(ri)
930 r = pr
931 } else {
932 r = newXmlSimpleReader(ri)
933 }
934
935 attrCheck := make(map[xml.Name]int)
936 dec := newDecoder(r, settings)
937
938 maxDepth := settings.MaxDepth
939 if maxDepth <= 0 {
940 maxDepth = defaultMaxDepth
941 }
942
943 var stack stack[*Element]
944 stack.push(e)
945 for {
946 if pr != nil {
947 pr.PeekPrepare(dec.InputOffset(), len(cdataPrefix))
948 }
949
950 t, err := dec.RawToken()
951
952 if settings.Permissive && settings.AutoClose != nil {
953 e.autoClose(&stack, t, settings.AutoClose)
954 }
955
956 switch {
957 case err == io.EOF:
958 if len(stack.data) != 1 {
959 return r.Bytes(), ErrXML
960 }
961 return r.Bytes(), nil
962 case err != nil:
963 return r.Bytes(), err
964 case stack.empty():
965 return r.Bytes(), ErrXML
966 }
967
968 top := stack.peek()
969
970 switch t := t.(type) {
971 case xml.StartElement:
972 if len(stack.data) > maxDepth {
973 return r.Bytes(), ErrMaxDepth
974 }
975 e := newElement(t.Name.Space, t.Name.Local, top)
976 if settings.PreserveDuplicateAttrs || len(t.Attr) < 2 {
977 for _, a := range t.Attr {
978 e.addAttr(a.Name.Space, a.Name.Local, a.Value)
979 }
980 } else {
981 for _, a := range t.Attr {
982 if i, contains := attrCheck[a.Name]; contains {
983 e.Attr[i].Value = a.Value
984 } else {
985 attrCheck[a.Name] = e.addAttr(a.Name.Space, a.Name.Local, a.Value)
986 }
987 }
988 clear(attrCheck)
989 }
990 stack.push(e)
991 case xml.EndElement:
992 if top.Tag != t.Name.Local || top.Space != t.Name.Space {
993 return r.Bytes(), ErrXML
994 }
995 stack.pop()
996 case xml.CharData:
997 data := string(t)
998 var flags charDataFlags
999 if pr != nil {
1000 peekBuf := pr.PeekFinalize()
1001 if bytes.Equal(peekBuf, cdataPrefix) {
1002 flags = cdataFlag
1003 } else if isWhitespace(data) {
1004 flags = whitespaceFlag
1005 }
1006 } else {
1007 if isWhitespace(data) {
1008 flags = whitespaceFlag
1009 }
1010 }
1011 newCharData(data, flags, top)
1012 case xml.Comment:
1013 newComment(string(t), top)
1014 case xml.Directive:
1015 newDirective(string(t), top)
1016 case xml.ProcInst:
1017 newProcInst(t.Target, string(t.Inst), top)
1018 }
1019 }
1020 }
1021
1022 // SelectAttr finds an element attribute matching the requested 'key' and, if
1023 // found, returns a pointer to the matching attribute. The function returns
1024 // nil if no matching attribute is found. The key may include a namespace
1025 // prefix followed by a colon.
1026 func (e *Element) SelectAttr(key string) *Attr {
1027 space, skey := spaceDecompose(key)
1028 for i, a := range e.Attr {
1029 if spaceMatch(space, a.Space) && skey == a.Key {
1030 return &e.Attr[i]
1031 }
1032 }
1033 return nil
1034 }
1035
1036 // SelectAttrValue finds an element attribute matching the requested 'key' and
1037 // returns its value if found. If no matching attribute is found, the function
1038 // returns the 'dflt' value instead. The key may include a namespace prefix
1039 // followed by a colon.
1040 func (e *Element) SelectAttrValue(key, dflt string) string {
1041 space, skey := spaceDecompose(key)
1042 for _, a := range e.Attr {
1043 if spaceMatch(space, a.Space) && skey == a.Key {
1044 return a.Value
1045 }
1046 }
1047 return dflt
1048 }
1049
1050 // ChildElements returns all elements that are children of this element.
1051 func (e *Element) ChildElements() []*Element {
1052 return slices.Collect(e.ChildElementsSeq())
1053 }
1054
1055 // ChildElementsSeq returns an iterator over all child elements of this
1056 // element.
1057 func (e *Element) ChildElementsSeq() iter.Seq[*Element] {
1058 return func(yield func(*Element) bool) {
1059 for _, t := range e.Child {
1060 if c, ok := t.(*Element); ok {
1061 if !yield(c) {
1062 return
1063 }
1064 }
1065 }
1066 }
1067 }
1068
1069 // SelectElement returns the first child element with the given 'tag' (i.e.,
1070 // name). The function returns nil if no child element matching the tag is
1071 // found. The tag may include a namespace prefix followed by a colon.
1072 func (e *Element) SelectElement(tag string) *Element {
1073 for element := range e.SelectElementsSeq(tag) {
1074 return element
1075 }
1076 return nil
1077 }
1078
1079 // SelectElements returns a slice of all child elements with the given 'tag'
1080 // (i.e., name). The tag may include a namespace prefix followed by a colon.
1081 func (e *Element) SelectElements(tag string) []*Element {
1082 return slices.Collect(e.SelectElementsSeq(tag))
1083 }
1084
1085 // SelectElementsSeq returns an iterator over all child elements with the
1086 // given 'tag' (i.e., name). The tag may include a namespace prefix followed
1087 // by a colon.
1088 func (e *Element) SelectElementsSeq(tag string) iter.Seq[*Element] {
1089 return func(yield func(*Element) bool) {
1090 space, stag := spaceDecompose(tag)
1091 for _, t := range e.Child {
1092 if c, ok := t.(*Element); ok && spaceMatch(space, c.Space) && stag == c.Tag {
1093 if !yield(c) {
1094 return
1095 }
1096 }
1097 }
1098 }
1099 }
1100
1101 // FindElement returns the first element matched by the XPath-like 'path'
1102 // string. The function returns nil if no child element is found using the
1103 // path. It panics if an invalid path string is supplied.
1104 func (e *Element) FindElement(path string) *Element {
1105 return e.FindElementPath(MustCompilePath(path))
1106 }
1107
1108 // FindElementPath returns the first element matched by the 'path' object. The
1109 // function returns nil if no element is found using the path.
1110 func (e *Element) FindElementPath(path Path) *Element {
1111 for element := range path.traverse(e) {
1112 return element
1113 }
1114 return nil
1115 }
1116
1117 // FindElements returns a slice of elements matched by the XPath-like 'path'
1118 // string. The function returns nil if no child element is found using the
1119 // path. It panics if an invalid path string is supplied.
1120 func (e *Element) FindElements(path string) []*Element {
1121 return slices.Collect(e.FindElementsSeq(path))
1122 }
1123
1124 // FindElementsSeq returns an iterator over elements matched by the XPath-like
1125 // 'path' string. This function uses Go's iterator support for
1126 // memory-efficient traversal. It panics if an invalid path string is
1127 // supplied.
1128 func (e *Element) FindElementsSeq(path string) iter.Seq[*Element] {
1129 return e.FindElementsPathSeq(MustCompilePath(path))
1130 }
1131
1132 // FindElementsPath returns a slice of elements matched by the 'path' object.
1133 func (e *Element) FindElementsPath(path Path) []*Element {
1134 return slices.Collect(e.FindElementsPathSeq(path))
1135 }
1136
1137 // FindElementsPathSeq returns an iterator over elements matched by the 'path'
1138 // object.
1139 func (e *Element) FindElementsPathSeq(path Path) iter.Seq[*Element] {
1140 return path.traverse(e)
1141 }
1142
1143 // NotNil returns the receiver element if it isn't nil; otherwise, it returns
1144 // an unparented element with an empty string tag. This function simplifies
1145 // the task of writing code to ignore not-found results from element queries.
1146 // For example, instead of writing this:
1147 //
1148 // if e := doc.SelectElement("enabled"); e != nil {
1149 // e.SetText("true")
1150 // }
1151 //
1152 // You could write this:
1153 //
1154 // doc.SelectElement("enabled").NotNil().SetText("true")
1155 func (e *Element) NotNil() *Element {
1156 if e == nil {
1157 return NewElement("")
1158 }
1159 return e
1160 }
1161
1162 // GetPath returns the absolute path of the element. The absolute path is the
1163 // full path from the document's root.
1164 func (e *Element) GetPath() string {
1165 path := []string{}
1166 for seg := e; seg != nil; seg = seg.Parent() {
1167 if seg.Tag != "" {
1168 path = append(path, seg.Tag)
1169 }
1170 }
1171
1172 // Reverse the path.
1173 for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
1174 path[i], path[j] = path[j], path[i]
1175 }
1176
1177 return "/" + strings.Join(path, "/")
1178 }
1179
1180 // GetRelativePath returns the path of this element relative to the 'source'
1181 // element. If the two elements are not part of the same element tree, then
1182 // the function returns the empty string.
1183 func (e *Element) GetRelativePath(source *Element) string {
1184 var path []*Element
1185
1186 if source == nil {
1187 return ""
1188 }
1189
1190 // Build a reverse path from the element toward the root. Stop if the
1191 // source element is encountered.
1192 var seg *Element
1193 for seg = e; seg != nil && seg != source; seg = seg.Parent() {
1194 path = append(path, seg)
1195 }
1196
1197 // If we found the source element, reverse the path and compose the
1198 // string.
1199 if seg == source {
1200 if len(path) == 0 {
1201 return "."
1202 }
1203 parts := []string{}
1204 for i := len(path) - 1; i >= 0; i-- {
1205 parts = append(parts, path[i].Tag)
1206 }
1207 return "./" + strings.Join(parts, "/")
1208 }
1209
1210 // The source wasn't encountered, so climb from the source element toward
1211 // the root of the tree until an element in the reversed path is
1212 // encountered.
1213
1214 findPathIndex := func(e *Element, path []*Element) int {
1215 for i, ee := range path {
1216 if e == ee {
1217 return i
1218 }
1219 }
1220 return -1
1221 }
1222
1223 climb := 0
1224 for seg = source; seg != nil; seg = seg.Parent() {
1225 i := findPathIndex(seg, path)
1226 if i >= 0 {
1227 path = path[:i] // truncate at found segment
1228 break
1229 }
1230 climb++
1231 }
1232
1233 // No element in the reversed path was encountered, so the two elements
1234 // must not be part of the same tree.
1235 if seg == nil {
1236 return ""
1237 }
1238
1239 // Reverse the (possibly truncated) path and prepend ".." segments to
1240 // climb.
1241 parts := []string{}
1242 for i := 0; i < climb; i++ {
1243 parts = append(parts, "..")
1244 }
1245 for i := len(path) - 1; i >= 0; i-- {
1246 parts = append(parts, path[i].Tag)
1247 }
1248 return strings.Join(parts, "/")
1249 }
1250
1251 // IndentWithSettings modifies the element and its child tree by inserting
1252 // character data tokens containing newlines and indentation. The behavior of
1253 // the indentation algorithm is configured by the indent settings. Because
1254 // this function indents the element as if it were at the root of a document,
1255 // it is most useful when called just before writing the element as an XML
1256 // fragment using WriteTo.
1257 func (e *Element) IndentWithSettings(s *IndentSettings) {
1258 e.indent(1, getIndentFunc(s), s)
1259 }
1260
1261 // indent recursively inserts proper indentation between an XML element's
1262 // child tokens.
1263 func (e *Element) indent(depth int, indent indentFunc, s *IndentSettings) {
1264 e.stripIndent(s)
1265 n := len(e.Child)
1266 if n == 0 {
1267 return
1268 }
1269
1270 oldChild := e.Child
1271 e.Child = make([]Token, 0, n*2+1)
1272 isCharData, firstNonCharData := false, true
1273 for _, c := range oldChild {
1274 // Insert NL+indent before child if it's not character data.
1275 // Exceptions: when it's the first non-character-data child, or when
1276 // the child is at root depth.
1277 _, isCharData = c.(*CharData)
1278 if !isCharData {
1279 if !firstNonCharData || depth > 0 {
1280 s := indent(depth)
1281 if s != "" {
1282 newCharData(s, whitespaceFlag, e)
1283 }
1284 }
1285 firstNonCharData = false
1286 }
1287
1288 e.addChild(c)
1289
1290 // Recursively process child elements.
1291 if ce, ok := c.(*Element); ok {
1292 ce.indent(depth+1, indent, s)
1293 }
1294 }
1295
1296 // Insert NL+indent before the last child.
1297 if !isCharData {
1298 if !firstNonCharData || depth > 0 {
1299 s := indent(depth - 1)
1300 if s != "" {
1301 newCharData(s, whitespaceFlag, e)
1302 }
1303 }
1304 }
1305 }
1306
1307 // stripIndent removes any previously inserted indentation.
1308 func (e *Element) stripIndent(s *IndentSettings) {
1309 // Count the number of non-indent child tokens
1310 n := len(e.Child)
1311 for _, c := range e.Child {
1312 if cd, ok := c.(*CharData); ok && cd.IsWhitespace() {
1313 n--
1314 }
1315 }
1316 if n == len(e.Child) {
1317 return
1318 }
1319 if n == 0 && len(e.Child) == 1 && s.PreserveLeafWhitespace {
1320 return
1321 }
1322
1323 // Strip out indent CharData
1324 newChild := make([]Token, n)
1325 j := 0
1326 for _, c := range e.Child {
1327 if cd, ok := c.(*CharData); ok && cd.IsWhitespace() {
1328 continue
1329 }
1330 newChild[j] = c
1331 newChild[j].setIndex(j)
1332 j++
1333 }
1334 e.Child = newChild
1335 }
1336
1337 // stripTrailingWhitespace removes any trailing whitespace CharData tokens
1338 // from the element's children.
1339 func (e *Element) stripTrailingWhitespace() {
1340 for i := len(e.Child) - 1; i >= 0; i-- {
1341 if cd, ok := e.Child[i].(*CharData); !ok || !cd.IsWhitespace() {
1342 e.Child = e.Child[:i+1]
1343 return
1344 }
1345 }
1346 }
1347
1348 // dup duplicates the element.
1349 func (e *Element) dup(parent *Element) Token {
1350 ne := &Element{
1351 Space: e.Space,
1352 Tag: e.Tag,
1353 Attr: make([]Attr, len(e.Attr)),
1354 Child: make([]Token, len(e.Child)),
1355 parent: parent,
1356 index: e.index,
1357 }
1358 for i, t := range e.Child {
1359 ne.Child[i] = t.dup(ne)
1360 }
1361 copy(ne.Attr, e.Attr)
1362 return ne
1363 }
1364
1365 // NextSibling returns this element's next sibling element. It returns nil if
1366 // there is no next sibling element.
1367 func (e *Element) NextSibling() *Element {
1368 if e.parent == nil {
1369 return nil
1370 }
1371 for i := e.index + 1; i < len(e.parent.Child); i++ {
1372 if s, ok := e.parent.Child[i].(*Element); ok {
1373 return s
1374 }
1375 }
1376 return nil
1377 }
1378
1379 // PrevSibling returns this element's preceding sibling element. It returns
1380 // nil if there is no preceding sibling element.
1381 func (e *Element) PrevSibling() *Element {
1382 if e.parent == nil {
1383 return nil
1384 }
1385 for i := e.index - 1; i >= 0; i-- {
1386 if s, ok := e.parent.Child[i].(*Element); ok {
1387 return s
1388 }
1389 }
1390 return nil
1391 }
1392
1393 // Parent returns this element's parent element. It returns nil if this
1394 // element has no parent.
1395 func (e *Element) Parent() *Element {
1396 return e.parent
1397 }
1398
1399 // Index returns the index of this element within its parent element's
1400 // list of child tokens. If this element has no parent, then the function
1401 // returns -1.
1402 func (e *Element) Index() int {
1403 return e.index
1404 }
1405
1406 // WriteTo serializes the element to the writer w.
1407 func (e *Element) WriteTo(w Writer, s *WriteSettings) {
1408 w.WriteByte('<')
1409 w.WriteString(e.FullTag())
1410 for _, a := range e.Attr {
1411 w.WriteByte(' ')
1412 a.WriteTo(w, s)
1413 }
1414 if len(e.Child) > 0 {
1415 w.WriteByte('>')
1416 for _, c := range e.Child {
1417 c.WriteTo(w, s)
1418 }
1419 w.Write([]byte{'<', '/'})
1420 w.WriteString(e.FullTag())
1421 w.WriteByte('>')
1422 } else {
1423 if s.CanonicalEndTags {
1424 w.Write([]byte{'>', '<', '/'})
1425 w.WriteString(e.FullTag())
1426 w.WriteByte('>')
1427 } else {
1428 w.Write([]byte{'/', '>'})
1429 }
1430 }
1431 }
1432
1433 // setParent replaces this element token's parent.
1434 func (e *Element) setParent(parent *Element) {
1435 e.parent = parent
1436 }
1437
1438 // setIndex sets this element token's index within its parent's Child slice.
1439 func (e *Element) setIndex(index int) {
1440 e.index = index
1441 }
1442
1443 // addChild adds a child token to the element e.
1444 func (e *Element) addChild(t Token) {
1445 t.setParent(e)
1446 t.setIndex(len(e.Child))
1447 e.Child = append(e.Child, t)
1448 }
1449
1450 // CreateAttr creates an attribute with the specified 'key' and 'value' and
1451 // adds it to this element. If an attribute with same key already exists on
1452 // this element, then its value is replaced. The key may include a namespace
1453 // prefix followed by a colon.
1454 func (e *Element) CreateAttr(key, value string) *Attr {
1455 space, skey := spaceDecompose(key)
1456
1457 for i, a := range e.Attr {
1458 if space == a.Space && skey == a.Key {
1459 e.Attr[i].Value = value
1460 return &e.Attr[i]
1461 }
1462 }
1463
1464 i := e.addAttr(space, skey, value)
1465 return &e.Attr[i]
1466 }
1467
1468 // addAttr is a helper function that adds an attribute to an element. Returns
1469 // the index of the added attribute.
1470 func (e *Element) addAttr(space, key, value string) int {
1471 a := Attr{
1472 Space: space,
1473 Key: key,
1474 Value: value,
1475 element: e,
1476 }
1477 e.Attr = append(e.Attr, a)
1478 return len(e.Attr) - 1
1479 }
1480
1481 // RemoveAttr removes the first attribute of this element whose key matches
1482 // 'key'. It returns a copy of the removed attribute if a match is found. If
1483 // no match is found, it returns nil. The key may include a namespace prefix
1484 // followed by a colon.
1485 func (e *Element) RemoveAttr(key string) *Attr {
1486 space, skey := spaceDecompose(key)
1487 for i, a := range e.Attr {
1488 if space == a.Space && skey == a.Key {
1489 e.Attr = append(e.Attr[0:i], e.Attr[i+1:]...)
1490 return &Attr{
1491 Space: a.Space,
1492 Key: a.Key,
1493 Value: a.Value,
1494 element: nil,
1495 }
1496 }
1497 }
1498 return nil
1499 }
1500
1501 // SortAttrs sorts this element's attributes lexicographically by key.
1502 func (e *Element) SortAttrs() {
1503 slices.SortFunc(e.Attr, func(a, b Attr) int {
1504 if v := strings.Compare(a.Space, b.Space); v != 0 {
1505 return v
1506 }
1507 return strings.Compare(a.Key, b.Key)
1508 })
1509 }
1510
1511 // FullKey returns this attribute's complete key, including namespace prefix
1512 // if present.
1513 func (a *Attr) FullKey() string {
1514 if a.Space == "" {
1515 return a.Key
1516 }
1517 return a.Space + ":" + a.Key
1518 }
1519
1520 // Element returns a pointer to the element containing this attribute.
1521 func (a *Attr) Element() *Element {
1522 return a.element
1523 }
1524
1525 // NamespaceURI returns the XML namespace URI associated with this attribute.
1526 // The function returns the empty string if the attribute is unprefixed or
1527 // if the attribute is part of the XML default namespace.
1528 func (a *Attr) NamespaceURI() string {
1529 if a.Space == "" {
1530 return ""
1531 }
1532 return a.element.findLocalNamespaceURI(a.Space)
1533 }
1534
1535 // WriteTo serializes the attribute to the writer.
1536 func (a *Attr) WriteTo(w Writer, s *WriteSettings) {
1537 w.WriteString(a.FullKey())
1538 if s.AttrSingleQuote {
1539 w.WriteString(`='`)
1540 } else {
1541 w.WriteString(`="`)
1542 }
1543 var m escapeMode
1544 if s.CanonicalAttrVal && !s.AttrSingleQuote {
1545 m = escapeCanonicalAttr
1546 } else {
1547 m = escapeNormal
1548 }
1549 escapeString(w, a.Value, m)
1550 if s.AttrSingleQuote {
1551 w.WriteByte('\'')
1552 } else {
1553 w.WriteByte('"')
1554 }
1555 }
1556
1557 // NewText creates an unparented CharData token containing simple text data.
1558 func NewText(text string) *CharData {
1559 return newCharData(text, 0, nil)
1560 }
1561
1562 // NewCData creates an unparented XML character CDATA section with 'data' as
1563 // its content.
1564 func NewCData(data string) *CharData {
1565 return newCharData(data, cdataFlag, nil)
1566 }
1567
1568 // NewCharData creates an unparented CharData token containing simple text
1569 // data.
1570 //
1571 // Deprecated: NewCharData is deprecated. Instead, use NewText, which does the
1572 // same thing.
1573 func NewCharData(data string) *CharData {
1574 return newCharData(data, 0, nil)
1575 }
1576
1577 // newCharData creates a character data token and binds it to a parent
1578 // element. If parent is nil, the CharData token remains unbound.
1579 func newCharData(data string, flags charDataFlags, parent *Element) *CharData {
1580 c := &CharData{
1581 Data: data,
1582 parent: nil,
1583 index: -1,
1584 flags: flags,
1585 }
1586 if parent != nil {
1587 parent.addChild(c)
1588 }
1589 return c
1590 }
1591
1592 // CreateText creates a CharData token containing simple text data and adds it
1593 // to the end of this element's list of child tokens.
1594 func (e *Element) CreateText(text string) *CharData {
1595 return newCharData(text, 0, e)
1596 }
1597
1598 // CreateCData creates a CharData token containing a CDATA section with 'data'
1599 // as its content and adds it to the end of this element's list of child
1600 // tokens.
1601 func (e *Element) CreateCData(data string) *CharData {
1602 return newCharData(data, cdataFlag, e)
1603 }
1604
1605 // CreateCharData creates a CharData token containing simple text data and
1606 // adds it to the end of this element's list of child tokens.
1607 //
1608 // Deprecated: CreateCharData is deprecated. Instead, use CreateText, which
1609 // does the same thing.
1610 func (e *Element) CreateCharData(data string) *CharData {
1611 return e.CreateText(data)
1612 }
1613
1614 // SetData modifies the content of the CharData token. In the case of a
1615 // CharData token containing simple text, the simple text is modified. In the
1616 // case of a CharData token containing a CDATA section, the CDATA section's
1617 // content is modified.
1618 func (c *CharData) SetData(text string) {
1619 c.Data = text
1620 if isWhitespace(text) {
1621 c.flags |= whitespaceFlag
1622 } else {
1623 c.flags &= ^whitespaceFlag
1624 }
1625 }
1626
1627 // IsCData returns true if this CharData token is contains a CDATA section. It
1628 // returns false if the CharData token contains simple text.
1629 func (c *CharData) IsCData() bool {
1630 return (c.flags & cdataFlag) != 0
1631 }
1632
1633 // IsWhitespace returns true if this CharData token contains only whitespace.
1634 func (c *CharData) IsWhitespace() bool {
1635 return (c.flags & whitespaceFlag) != 0
1636 }
1637
1638 // Parent returns this CharData token's parent element, or nil if it has no
1639 // parent.
1640 func (c *CharData) Parent() *Element {
1641 return c.parent
1642 }
1643
1644 // Index returns the index of this CharData token within its parent element's
1645 // list of child tokens. If this CharData token has no parent, then the
1646 // function returns -1.
1647 func (c *CharData) Index() int {
1648 return c.index
1649 }
1650
1651 // WriteTo serializes character data to the writer.
1652 func (c *CharData) WriteTo(w Writer, s *WriteSettings) {
1653 if c.IsCData() {
1654 w.WriteString(`<![CDATA[`)
1655 sanitizeCData(w, c.Data)
1656 w.WriteString(`]]>`)
1657 } else {
1658 var m escapeMode
1659 if s.CanonicalText {
1660 m = escapeCanonicalText
1661 } else {
1662 m = escapeNormal
1663 }
1664 escapeString(w, c.Data, m)
1665 }
1666 }
1667
1668 // dup duplicates the character data.
1669 func (c *CharData) dup(parent *Element) Token {
1670 return &CharData{
1671 Data: c.Data,
1672 flags: c.flags,
1673 parent: parent,
1674 index: c.index,
1675 }
1676 }
1677
1678 // setParent replaces the character data token's parent.
1679 func (c *CharData) setParent(parent *Element) {
1680 c.parent = parent
1681 }
1682
1683 // setIndex sets the CharData token's index within its parent element's Child
1684 // slice.
1685 func (c *CharData) setIndex(index int) {
1686 c.index = index
1687 }
1688
1689 // NewComment creates an unparented comment token.
1690 func NewComment(comment string) *Comment {
1691 return newComment(comment, nil)
1692 }
1693
1694 // NewComment creates a comment token and sets its parent element to 'parent'.
1695 func newComment(comment string, parent *Element) *Comment {
1696 c := &Comment{
1697 Data: comment,
1698 parent: nil,
1699 index: -1,
1700 }
1701 if parent != nil {
1702 parent.addChild(c)
1703 }
1704 return c
1705 }
1706
1707 // CreateComment creates a comment token using the specified 'comment' string
1708 // and adds it as the last child token of this element.
1709 func (e *Element) CreateComment(comment string) *Comment {
1710 return newComment(comment, e)
1711 }
1712
1713 // dup duplicates the comment.
1714 func (c *Comment) dup(parent *Element) Token {
1715 return &Comment{
1716 Data: c.Data,
1717 parent: parent,
1718 index: c.index,
1719 }
1720 }
1721
1722 // Parent returns comment token's parent element, or nil if it has no parent.
1723 func (c *Comment) Parent() *Element {
1724 return c.parent
1725 }
1726
1727 // Index returns the index of this Comment token within its parent element's
1728 // list of child tokens. If this Comment token has no parent, then the
1729 // function returns -1.
1730 func (c *Comment) Index() int {
1731 return c.index
1732 }
1733
1734 // WriteTo serialies the comment to the writer.
1735 func (c *Comment) WriteTo(w Writer, s *WriteSettings) {
1736 w.WriteString("<!--")
1737 sanitizeComment(w, c.Data)
1738 w.WriteString("-->")
1739 }
1740
1741 // setParent replaces the comment token's parent.
1742 func (c *Comment) setParent(parent *Element) {
1743 c.parent = parent
1744 }
1745
1746 // setIndex sets the Comment token's index within its parent element's Child
1747 // slice.
1748 func (c *Comment) setIndex(index int) {
1749 c.index = index
1750 }
1751
1752 // NewDirective creates an unparented XML directive token.
1753 func NewDirective(data string) *Directive {
1754 return newDirective(data, nil)
1755 }
1756
1757 // newDirective creates an XML directive and binds it to a parent element. If
1758 // parent is nil, the Directive remains unbound.
1759 func newDirective(data string, parent *Element) *Directive {
1760 d := &Directive{
1761 Data: data,
1762 parent: nil,
1763 index: -1,
1764 }
1765 if parent != nil {
1766 parent.addChild(d)
1767 }
1768 return d
1769 }
1770
1771 // CreateDirective creates an XML directive token with the specified 'data'
1772 // value and adds it as the last child token of this element.
1773 func (e *Element) CreateDirective(data string) *Directive {
1774 return newDirective(data, e)
1775 }
1776
1777 // dup duplicates the directive.
1778 func (d *Directive) dup(parent *Element) Token {
1779 return &Directive{
1780 Data: d.Data,
1781 parent: parent,
1782 index: d.index,
1783 }
1784 }
1785
1786 // Parent returns directive token's parent element, or nil if it has no
1787 // parent.
1788 func (d *Directive) Parent() *Element {
1789 return d.parent
1790 }
1791
1792 // Index returns the index of this Directive token within its parent element's
1793 // list of child tokens. If this Directive token has no parent, then the
1794 // function returns -1.
1795 func (d *Directive) Index() int {
1796 return d.index
1797 }
1798
1799 // WriteTo serializes the XML directive to the writer.
1800 func (d *Directive) WriteTo(w Writer, s *WriteSettings) {
1801 w.WriteString("<!")
1802 sanitizeDirective(w, d.Data)
1803 w.WriteString(">")
1804 }
1805
1806 // setParent replaces the directive token's parent.
1807 func (d *Directive) setParent(parent *Element) {
1808 d.parent = parent
1809 }
1810
1811 // setIndex sets the Directive token's index within its parent element's Child
1812 // slice.
1813 func (d *Directive) setIndex(index int) {
1814 d.index = index
1815 }
1816
1817 // NewProcInst creates an unparented XML processing instruction.
1818 func NewProcInst(target, inst string) *ProcInst {
1819 return newProcInst(target, inst, nil)
1820 }
1821
1822 // newProcInst creates an XML processing instruction and binds it to a parent
1823 // element. If parent is nil, the ProcInst remains unbound.
1824 func newProcInst(target, inst string, parent *Element) *ProcInst {
1825 p := &ProcInst{
1826 Target: target,
1827 Inst: inst,
1828 parent: nil,
1829 index: -1,
1830 }
1831 if parent != nil {
1832 parent.addChild(p)
1833 }
1834 return p
1835 }
1836
1837 // CreateProcInst creates an XML processing instruction token with the
1838 // specified 'target' and instruction 'inst'. It is then added as the last
1839 // child token of this element.
1840 func (e *Element) CreateProcInst(target, inst string) *ProcInst {
1841 return newProcInst(target, inst, e)
1842 }
1843
1844 // dup duplicates the procinst.
1845 func (p *ProcInst) dup(parent *Element) Token {
1846 return &ProcInst{
1847 Target: p.Target,
1848 Inst: p.Inst,
1849 parent: parent,
1850 index: p.index,
1851 }
1852 }
1853
1854 // Parent returns processing instruction token's parent element, or nil if it
1855 // has no parent.
1856 func (p *ProcInst) Parent() *Element {
1857 return p.parent
1858 }
1859
1860 // Index returns the index of this ProcInst token within its parent element's
1861 // list of child tokens. If this ProcInst token has no parent, then the
1862 // function returns -1.
1863 func (p *ProcInst) Index() int {
1864 return p.index
1865 }
1866
1867 // WriteTo serializes the processing instruction to the writer.
1868 func (p *ProcInst) WriteTo(w Writer, s *WriteSettings) {
1869 w.WriteString("<?")
1870 sanitizeProcInst(w, p.Target)
1871 if p.Inst != "" {
1872 w.WriteByte(' ')
1873 sanitizeProcInst(w, p.Inst)
1874 }
1875 w.WriteString("?>")
1876 }
1877
1878 // setParent replaces the processing instruction token's parent.
1879 func (p *ProcInst) setParent(parent *Element) {
1880 p.parent = parent
1881 }
1882
1883 // setIndex sets the processing instruction token's index within its parent
1884 // element's Child slice.
1885 func (p *ProcInst) setIndex(index int) {
1886 p.index = index
1887 }