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 return e.Parent().RemoveChild(e) != nil
1410 }
1411
1412 // WriteTo serializes the element to the writer w.
1413 func (e *Element) WriteTo(w Writer, s *WriteSettings) {
1414 w.WriteByte('<')
1415 w.WriteString(e.FullTag())
1416 for _, a := range e.Attr {
1417 w.WriteByte(' ')
1418 a.WriteTo(w, s)
1419 }
1420 if len(e.Child) > 0 {
1421 w.WriteByte('>')
1422 for _, c := range e.Child {
1423 c.WriteTo(w, s)
1424 }
1425 w.Write([]byte{'<', '/'})
1426 w.WriteString(e.FullTag())
1427 w.WriteByte('>')
1428 } else {
1429 if s.CanonicalEndTags {
1430 w.Write([]byte{'>', '<', '/'})
1431 w.WriteString(e.FullTag())
1432 w.WriteByte('>')
1433 } else {
1434 w.Write([]byte{'/', '>'})
1435 }
1436 }
1437 }
1438
1439 // setParent replaces this element token's parent.
1440 func (e *Element) setParent(parent *Element) {
1441 e.parent = parent
1442 }
1443
1444 // setIndex sets this element token's index within its parent's Child slice.
1445 func (e *Element) setIndex(index int) {
1446 e.index = index
1447 }
1448
1449 // addChild adds a child token to the element e.
1450 func (e *Element) addChild(t Token) {
1451 t.setParent(e)
1452 t.setIndex(len(e.Child))
1453 e.Child = append(e.Child, t)
1454 }
1455
1456 // CreateAttr creates an attribute with the specified 'key' and 'value' and
1457 // adds it to this element. If an attribute with same key already exists on
1458 // this element, then its value is replaced. The key may include a namespace
1459 // prefix followed by a colon.
1460 func (e *Element) CreateAttr(key, value string) *Attr {
1461 space, skey := spaceDecompose(key)
1462
1463 for i, a := range e.Attr {
1464 if space == a.Space && skey == a.Key {
1465 e.Attr[i].Value = value
1466 return &e.Attr[i]
1467 }
1468 }
1469
1470 i := e.addAttr(space, skey, value)
1471 return &e.Attr[i]
1472 }
1473
1474 // addAttr is a helper function that adds an attribute to an element. Returns
1475 // the index of the added attribute.
1476 func (e *Element) addAttr(space, key, value string) int {
1477 a := Attr{
1478 Space: space,
1479 Key: key,
1480 Value: value,
1481 element: e,
1482 }
1483 e.Attr = append(e.Attr, a)
1484 return len(e.Attr) - 1
1485 }
1486
1487 // RemoveAttr removes the first attribute of this element whose key matches
1488 // 'key'. It returns a copy of the removed attribute if a match is found. If
1489 // no match is found, it returns nil. The key may include a namespace prefix
1490 // followed by a colon.
1491 func (e *Element) RemoveAttr(key string) *Attr {
1492 space, skey := spaceDecompose(key)
1493 for i, a := range e.Attr {
1494 if space == a.Space && skey == a.Key {
1495 e.Attr = append(e.Attr[0:i], e.Attr[i+1:]...)
1496 return &Attr{
1497 Space: a.Space,
1498 Key: a.Key,
1499 Value: a.Value,
1500 element: nil,
1501 }
1502 }
1503 }
1504 return nil
1505 }
1506
1507 // SortAttrs sorts this element's attributes lexicographically by key.
1508 func (e *Element) SortAttrs() {
1509 slices.SortFunc(e.Attr, func(a, b Attr) int {
1510 if v := strings.Compare(a.Space, b.Space); v != 0 {
1511 return v
1512 }
1513 return strings.Compare(a.Key, b.Key)
1514 })
1515 }
1516
1517 // FullKey returns this attribute's complete key, including namespace prefix
1518 // if present.
1519 func (a *Attr) FullKey() string {
1520 if a.Space == "" {
1521 return a.Key
1522 }
1523 return a.Space + ":" + a.Key
1524 }
1525
1526 // Element returns a pointer to the element containing this attribute.
1527 func (a *Attr) Element() *Element {
1528 return a.element
1529 }
1530
1531 // NamespaceURI returns the XML namespace URI associated with this attribute.
1532 // The function returns the empty string if the attribute is unprefixed or
1533 // if the attribute is part of the XML default namespace.
1534 func (a *Attr) NamespaceURI() string {
1535 if a.Space == "" {
1536 return ""
1537 }
1538 return a.element.findLocalNamespaceURI(a.Space)
1539 }
1540
1541 // WriteTo serializes the attribute to the writer.
1542 func (a *Attr) WriteTo(w Writer, s *WriteSettings) {
1543 w.WriteString(a.FullKey())
1544 if s.AttrSingleQuote {
1545 w.WriteString(`='`)
1546 } else {
1547 w.WriteString(`="`)
1548 }
1549 var m escapeMode
1550 if s.CanonicalAttrVal && !s.AttrSingleQuote {
1551 m = escapeCanonicalAttr
1552 } else {
1553 m = escapeNormal
1554 }
1555 escapeString(w, a.Value, m)
1556 if s.AttrSingleQuote {
1557 w.WriteByte('\'')
1558 } else {
1559 w.WriteByte('"')
1560 }
1561 }
1562
1563 // NewText creates an unparented CharData token containing simple text data.
1564 func NewText(text string) *CharData {
1565 return newCharData(text, 0, nil)
1566 }
1567
1568 // NewCData creates an unparented XML character CDATA section with 'data' as
1569 // its content.
1570 func NewCData(data string) *CharData {
1571 return newCharData(data, cdataFlag, nil)
1572 }
1573
1574 // NewCharData creates an unparented CharData token containing simple text
1575 // data.
1576 //
1577 // Deprecated: NewCharData is deprecated. Instead, use NewText, which does the
1578 // same thing.
1579 func NewCharData(data string) *CharData {
1580 return newCharData(data, 0, nil)
1581 }
1582
1583 // newCharData creates a character data token and binds it to a parent
1584 // element. If parent is nil, the CharData token remains unbound.
1585 func newCharData(data string, flags charDataFlags, parent *Element) *CharData {
1586 c := &CharData{
1587 Data: data,
1588 parent: nil,
1589 index: -1,
1590 flags: flags,
1591 }
1592 if parent != nil {
1593 parent.addChild(c)
1594 }
1595 return c
1596 }
1597
1598 // CreateText creates a CharData token containing simple text data and adds it
1599 // to the end of this element's list of child tokens.
1600 func (e *Element) CreateText(text string) *CharData {
1601 return newCharData(text, 0, e)
1602 }
1603
1604 // CreateCData creates a CharData token containing a CDATA section with 'data'
1605 // as its content and adds it to the end of this element's list of child
1606 // tokens.
1607 func (e *Element) CreateCData(data string) *CharData {
1608 return newCharData(data, cdataFlag, e)
1609 }
1610
1611 // CreateCharData creates a CharData token containing simple text data and
1612 // adds it to the end of this element's list of child tokens.
1613 //
1614 // Deprecated: CreateCharData is deprecated. Instead, use CreateText, which
1615 // does the same thing.
1616 func (e *Element) CreateCharData(data string) *CharData {
1617 return e.CreateText(data)
1618 }
1619
1620 // SetData modifies the content of the CharData token. In the case of a
1621 // CharData token containing simple text, the simple text is modified. In the
1622 // case of a CharData token containing a CDATA section, the CDATA section's
1623 // content is modified.
1624 func (c *CharData) SetData(text string) {
1625 c.Data = text
1626 if isWhitespace(text) {
1627 c.flags |= whitespaceFlag
1628 } else {
1629 c.flags &= ^whitespaceFlag
1630 }
1631 }
1632
1633 // IsCData returns true if this CharData token contains a CDATA section. It
1634 // returns false if the CharData token contains simple text.
1635 func (c *CharData) IsCData() bool {
1636 return (c.flags & cdataFlag) != 0
1637 }
1638
1639 // IsWhitespace returns true if this CharData token contains only whitespace.
1640 func (c *CharData) IsWhitespace() bool {
1641 return (c.flags & whitespaceFlag) != 0
1642 }
1643
1644 // Parent returns the CharData token's parent element, or nil if the token has
1645 // no parent.
1646 func (c *CharData) Parent() *Element {
1647 return c.parent
1648 }
1649
1650 // Index returns the index of the CharData token within its parent element's
1651 // list of child tokens. If the CharData token has no parent, the function
1652 // returns -1.
1653 func (c *CharData) Index() int {
1654 return c.index
1655 }
1656
1657 // Remove attempts to remove the CharData token from the parent element that
1658 // contains it. If the CharData token has no parent, the function returns
1659 // false.
1660 func (c *CharData) Remove() bool {
1661 return c.Parent().RemoveChild(c) != nil
1662 }
1663
1664 // WriteTo serializes CharData token to the writer.
1665 func (c *CharData) WriteTo(w Writer, s *WriteSettings) {
1666 if c.IsCData() {
1667 w.WriteString(`<![CDATA[`)
1668 sanitizeCData(w, c.Data)
1669 w.WriteString(`]]>`)
1670 } else {
1671 var m escapeMode
1672 if s.CanonicalText {
1673 m = escapeCanonicalText
1674 } else {
1675 m = escapeNormal
1676 }
1677 escapeString(w, c.Data, m)
1678 }
1679 }
1680
1681 // dup duplicates the character data.
1682 func (c *CharData) dup(parent *Element) Token {
1683 return &CharData{
1684 Data: c.Data,
1685 flags: c.flags,
1686 parent: parent,
1687 index: c.index,
1688 }
1689 }
1690
1691 // setParent replaces the character data token's parent.
1692 func (c *CharData) setParent(parent *Element) {
1693 c.parent = parent
1694 }
1695
1696 // setIndex sets the CharData token's index within its parent element's Child
1697 // slice.
1698 func (c *CharData) setIndex(index int) {
1699 c.index = index
1700 }
1701
1702 // NewComment creates an unparented comment token.
1703 func NewComment(comment string) *Comment {
1704 return newComment(comment, nil)
1705 }
1706
1707 // NewComment creates a comment token and sets its parent element to 'parent'.
1708 func newComment(comment string, parent *Element) *Comment {
1709 c := &Comment{
1710 Data: comment,
1711 parent: nil,
1712 index: -1,
1713 }
1714 if parent != nil {
1715 parent.addChild(c)
1716 }
1717 return c
1718 }
1719
1720 // CreateComment creates a comment token using the specified 'comment' string
1721 // and adds it as the last child token of this element.
1722 func (e *Element) CreateComment(comment string) *Comment {
1723 return newComment(comment, e)
1724 }
1725
1726 // dup duplicates the comment.
1727 func (c *Comment) dup(parent *Element) Token {
1728 return &Comment{
1729 Data: c.Data,
1730 parent: parent,
1731 index: c.index,
1732 }
1733 }
1734
1735 // Parent returns the comment's parent element, or nil if the comment has no
1736 // parent.
1737 func (c *Comment) Parent() *Element {
1738 return c.parent
1739 }
1740
1741 // Index returns the index of the comment within its parent element's list of
1742 // child tokens. If the comment has no parent, the function returns -1.
1743 func (c *Comment) Index() int {
1744 return c.index
1745 }
1746
1747 // Remove attempts to remove the comment from the parent element that contains
1748 // it. If the comment has no parent, the function returns false.
1749 func (c *Comment) Remove() bool {
1750 return c.Parent().RemoveChild(c) != nil
1751 }
1752
1753 // WriteTo serializes the comment to the writer.
1754 func (c *Comment) WriteTo(w Writer, s *WriteSettings) {
1755 w.WriteString("<!--")
1756 sanitizeComment(w, c.Data)
1757 w.WriteString("-->")
1758 }
1759
1760 // setParent replaces the comment token's parent.
1761 func (c *Comment) setParent(parent *Element) {
1762 c.parent = parent
1763 }
1764
1765 // setIndex sets the Comment token's index within its parent element's Child
1766 // slice.
1767 func (c *Comment) setIndex(index int) {
1768 c.index = index
1769 }
1770
1771 // NewDirective creates an unparented XML directive token.
1772 func NewDirective(data string) *Directive {
1773 return newDirective(data, nil)
1774 }
1775
1776 // newDirective creates an XML directive and binds it to a parent element. If
1777 // parent is nil, the Directive remains unbound.
1778 func newDirective(data string, parent *Element) *Directive {
1779 d := &Directive{
1780 Data: data,
1781 parent: nil,
1782 index: -1,
1783 }
1784 if parent != nil {
1785 parent.addChild(d)
1786 }
1787 return d
1788 }
1789
1790 // CreateDirective creates an XML directive token with the specified 'data'
1791 // value and adds it as the last child token of this element.
1792 func (e *Element) CreateDirective(data string) *Directive {
1793 return newDirective(data, e)
1794 }
1795
1796 // dup duplicates the directive.
1797 func (d *Directive) dup(parent *Element) Token {
1798 return &Directive{
1799 Data: d.Data,
1800 parent: parent,
1801 index: d.index,
1802 }
1803 }
1804
1805 // Parent returns the XML directive's parent element, or nil if it has no
1806 // parent.
1807 func (d *Directive) Parent() *Element {
1808 return d.parent
1809 }
1810
1811 // Index returns the index of the XML directive within its parent element's
1812 // list of child tokens. If the directive has no parent, the function returns
1813 // -1.
1814 func (d *Directive) Index() int {
1815 return d.index
1816 }
1817
1818 // Remove attempts to remove the XML directive from the parent element that
1819 // contains it. If the directive has no parent, the function returns false.
1820 func (d *Directive) Remove() bool {
1821 return d.Parent().RemoveChild(d) != nil
1822 }
1823
1824 // WriteTo serializes the XML directive to the writer.
1825 func (d *Directive) WriteTo(w Writer, s *WriteSettings) {
1826 w.WriteString("<!")
1827 sanitizeDirective(w, d.Data)
1828 w.WriteString(">")
1829 }
1830
1831 // setParent replaces the directive token's parent.
1832 func (d *Directive) setParent(parent *Element) {
1833 d.parent = parent
1834 }
1835
1836 // setIndex sets the Directive token's index within its parent element's Child
1837 // slice.
1838 func (d *Directive) setIndex(index int) {
1839 d.index = index
1840 }
1841
1842 // NewProcInst creates an unparented XML processing instruction.
1843 func NewProcInst(target, inst string) *ProcInst {
1844 return newProcInst(target, inst, nil)
1845 }
1846
1847 // newProcInst creates an XML processing instruction and binds it to a parent
1848 // element. If parent is nil, the ProcInst remains unbound.
1849 func newProcInst(target, inst string, parent *Element) *ProcInst {
1850 p := &ProcInst{
1851 Target: target,
1852 Inst: inst,
1853 parent: nil,
1854 index: -1,
1855 }
1856 if parent != nil {
1857 parent.addChild(p)
1858 }
1859 return p
1860 }
1861
1862 // CreateProcInst creates an XML processing instruction token with the
1863 // specified 'target' and instruction 'inst'. It is then added as the last
1864 // child token of this element.
1865 func (e *Element) CreateProcInst(target, inst string) *ProcInst {
1866 return newProcInst(target, inst, e)
1867 }
1868
1869 // dup duplicates the procinst.
1870 func (p *ProcInst) dup(parent *Element) Token {
1871 return &ProcInst{
1872 Target: p.Target,
1873 Inst: p.Inst,
1874 parent: parent,
1875 index: p.index,
1876 }
1877 }
1878
1879 // Parent returns XML processing instruction's parent element, or nil if it
1880 // has no parent.
1881 func (p *ProcInst) Parent() *Element {
1882 return p.parent
1883 }
1884
1885 // Index returns the index of the XML processing instruction within its parent
1886 // element's list of child tokens. If the processing instruction has no
1887 // parent, the function returns -1.
1888 func (p *ProcInst) Index() int {
1889 return p.index
1890 }
1891
1892 // Remove attempts to remove the XML processing instruction from the parent
1893 // element that contains it. If the processing instruction has no parent, the
1894 // function returns false.
1895 func (p *ProcInst) Remove() bool {
1896 return p.Parent().RemoveChild(p) != nil
1897 }
1898
1899 // WriteTo serializes the XML processing instruction to the writer.
1900 func (p *ProcInst) WriteTo(w Writer, s *WriteSettings) {
1901 w.WriteString("<?")
1902 sanitizeProcInst(w, p.Target)
1903 if p.Inst != "" {
1904 w.WriteByte(' ')
1905 sanitizeProcInst(w, p.Inst)
1906 }
1907 w.WriteString("?>")
1908 }
1909
1910 // setParent replaces the processing instruction token's parent.
1911 func (p *ProcInst) setParent(parent *Element) {
1912 p.parent = parent
1913 }
1914
1915 // setIndex sets the processing instruction token's index within its parent
1916 // element's Child slice.
1917 func (p *ProcInst) setIndex(index int) {
1918 p.index = index
1919 }