Debian Codegraph @

etree.go

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