xot 0.31.2

Full-featured XML tree library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use crate::unpretty::remove_insignificant_whitespace;
use crate::xotdata::{Node, Xot};
use crate::{xmlname, MutableAttributes, MutableNamespaces, NamespaceId, PrefixId};

use crate::access::NodeEdge;
use crate::error::Error;
use crate::id::NameId;
use crate::xmlvalue::{Value, ValueCategory, ValueType};

/// ## Manipulation
///
/// These methods maintain a well-formed XML structure:
/// - There is only one document element under the document node which cannot
///   be removed.
/// - The only other nodes that can exist directly under the document node are
///   comments and processing instructions.
/// - You cannot add a node to a node that is not an element or the document
///   node.
///
/// Note that you can use these manipulation methods to move nodes between
/// trees -- if you append a node that's in another tree, that node is first
/// detached from the other tree before it's inserted into the new location.
///
/// If text consolidation is enabled (the default), then also ensures that text
/// nodes are consolidated: two text nodes never appear consecutively. If you
/// add a text node after or before another text node, the text is appended to
/// the existing text node, and the added text node is removed. This also
/// happens if you remove a node causing two text nodes to be adjacent; the
/// second text node is removed.
///
/// During parsing it's also guaranteed that text and CDATA content that is
/// adjacent is consolidated into a single node.
///
/// You can disable and enable text consolidation using
/// [`Xot::set_text_consolidation`].
///
/// Text node consolidation example:
/// ```rust
/// use xot::Xot;
///
/// let mut xot = Xot::new();
/// let root = xot.parse(r#"<doc>First<s/>Second</doc>"#)?;
///
/// let doc_el = xot.document_element(root).unwrap();
/// let children = xot.children(doc_el).collect::<Vec<_>>();
/// let first = children[0];
/// let s = children[1];
/// let second = children[2];
///
/// // Now we remove s from the document
/// xot.remove(s)?;
///
/// // The text nodes are now adjacent, so the second text node is removed
/// // and merged with the first text node.
///
/// let children = xot.children(doc_el).collect::<Vec<_>>();
/// assert_eq!(children.len(), 1);
/// assert_eq!(xot.text_str(children[0]).unwrap(), "FirstSecond");
///
/// # Ok::<(), xot::Error>(())
/// ```
impl Xot {
    /// Append a child to the end of the children of the given parent.
    ///
    /// It is now the new last node of the parent.
    ///
    /// Append returns an error if you place a node in a location that is not
    /// allowed, such appending a node to a text node, or appending a new
    /// element to the root (there can be only one document element).
    ///
    /// See also the convenience methods [`Xot::append_element`],
    /// [`Xot::append_text`], [`Xot::append_comment`] and
    /// [`Xot::append_processing_instruction`].
    ///
    /// ```rust
    ///
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    ///
    /// let root = xot.parse(r#"<doc><p>Example</p></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    ///
    /// let p_name = xot.add_name("p");
    /// let p_el = xot.new_element(p_name);
    /// xot.append(doc_el, p_el)?;
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc><p>Example</p><p/></doc>"#);
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn append(&mut self, parent: Node, child: Node) -> Result<(), Error> {
        self.add_structure_check(Some(parent), child)?;
        self.remove_consolidate_text_nodes(self.previous_sibling(child), self.next_sibling(child));
        if self.add_consolidate_text_nodes(child, self.last_child(parent), None) {
            return Ok(());
        }
        parent.get().checked_append(child.get(), self.arena_mut())?;
        Ok(())
    }

    /// Append namespace node to parent node.
    ///
    /// If the namespace prefix already exists, instead of appending the node,
    /// updates the existing node.
    ///
    /// Returns the node that was inserted, or if an existing node was updated,
    /// this node.
    ///
    /// Note that an easier way to add namespace prefixes is through
    /// [`Xot::namespaces_mut()`]. This method is only useful if you have
    /// independent namespace nodes.
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc/>"#)?;
    /// let doc_el = xot.document_element(root)?;
    ///
    /// let prefix = xot.add_prefix("foo");
    /// let namespace = xot.add_namespace("http://example.com");
    /// let namespace2 = xot.add_namespace("http://example.com/2");
    /// let node = xot.new_namespace_node(prefix, namespace);
    /// let added_node = xot.append_namespace_node(doc_el, node)?;
    ///
    /// // since the node didn't yet exist, it's the node we got
    /// assert_eq!(added_node, node);
    ///
    /// assert_eq!(xot.to_string(root).unwrap(), r#"<doc xmlns:foo="http://example.com"/>"#);
    ///
    /// // If we append a node with the same prefix, the existing one is
    /// // updated.
    ///
    /// let new_node = xot.new_namespace_node(prefix, namespace2);
    /// let updated_node = xot.append_namespace_node(doc_el, new_node)?;
    ///
    /// // the updated node is the original not, not the new node
    /// assert_eq!(updated_node, node);
    /// assert_ne!(updated_node, new_node);
    ///
    /// assert_eq!(xot.to_string(root).unwrap(), r#"<doc xmlns:foo="http://example.com/2"/>"#);
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn append_namespace_node(&mut self, parent: Node, child: Node) -> Result<Node, Error> {
        if !self.is_element(parent) {
            return Err(Error::InvalidOperation(
                "Cannot add namespace node to non-element node".to_string(),
            ));
        }
        if !self.is_namespace_node(child) {
            return Err(Error::InvalidOperation(
                "Cannot add non-namespace node as namespace".to_string(),
            ));
        }

        let mut namespaces = self.namespaces_mut(parent);
        Ok(namespaces.insert_node(child))
    }

    /// Append an [`xmlname::CreateNamespace`]
    ///
    /// This creates a namespace node for the given namespace and prefix, and
    /// then returns this node (or previously updated node).
    ///
    /// ```rust
    /// use xot::{Xot, xmlname};
    ///
    /// let mut xot = Xot::new();
    /// let namespace = xmlname::CreateNamespace::new(&mut xot, "foo", "http://example.com");
    /// let root = xot.parse(r#"<doc/>"#)?;
    /// let doc_el = xot.document_element(root)?;
    /// xot.append_namespace(doc_el, &namespace)?;
    ///
    /// assert_eq!(xot.to_string(root).unwrap(), r#"<doc xmlns:foo="http://example.com"/>"#);
    ///
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn append_namespace(
        &mut self,
        parent: Node,
        namespace: &xmlname::CreateNamespace,
    ) -> Result<Node, Error> {
        let child = self.new_namespace_node(namespace.prefix_id(), namespace.namespace_id());
        self.append_namespace_node(parent, child)
    }

    /// Append attribute node to parent node.
    ///
    /// If the attribute name already exists, instead of appending the node,
    /// updates the existing node.
    ///
    /// Returns the node that was inserted, or if an existing node was updated,
    /// this node.
    ///
    /// Note that an easier way to add attributes is through
    /// [`Xot::attributes_mut()`]. This method is only useful if you have
    /// independent attribute nodes.
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc/>"#)?;
    /// let doc_el = xot.document_element(root)?;
    ///
    /// let foo = xot.add_name("foo");
    ///
    /// let node = xot.new_attribute_node(foo, "FOO".to_string());
    /// let added_node = xot.append_attribute_node(doc_el, node)?;
    ///
    /// // Since the node didn't yet exist, it's the one we get
    /// assert_eq!(added_node, node);
    ///
    /// assert_eq!(xot.to_string(root).unwrap(), r#"<doc foo="FOO"/>"#);
    ///
    /// // If we append a node with the same name, the existing one is
    /// // updated.
    ///
    /// let new_node = xot.new_attribute_node(foo, "FOO2".to_string());
    /// let updated_node = xot.append_attribute_node(doc_el, new_node)?;
    ///
    /// // the updated node is the original not, not the new node
    /// assert_eq!(updated_node, node);
    /// assert_ne!(updated_node, new_node);
    ///
    /// assert_eq!(xot.to_string(root).unwrap(), r#"<doc foo="FOO2"/>"#);
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn append_attribute_node(&mut self, parent: Node, child: Node) -> Result<Node, Error> {
        if !self.is_element(parent) {
            return Err(Error::InvalidOperation(
                "Cannot add attribute node to non-element node".to_string(),
            ));
        }
        if !self.is_attribute_node(child) {
            return Err(Error::InvalidOperation(
                "Cannot add non-attribute node as attribute".to_string(),
            ));
        }

        let mut attributes = self.attributes_mut(parent);
        Ok(attributes.insert_node(child))
    }

    /// Append any node, including namespace and attribute nodes.
    ///
    /// Namespace and attributes are appended in their respective places, and
    /// normal child nodes are appended in the end.
    ///
    /// Returns the node that was appended or, in case of attributes or
    /// namespaces that already existed, updated.
    pub fn any_append(&mut self, parent: Node, child: Node) -> Result<Node, Error> {
        match self.value_type(child) {
            ValueType::Namespace => self.append_namespace_node(parent, child),
            ValueType::Attribute => self.append_attribute_node(parent, child),
            _ => {
                self.append(parent, child)?;
                Ok(child)
            }
        }
    }

    /// Append a text node to a parent node given text.
    ///
    /// ```rust
    ///
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc><p>Example</p></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    ///
    /// xot.append_text(doc_el, "Hello")?;
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc><p>Example</p>Hello</doc>"#);
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn append_text(&mut self, parent: Node, text: &str) -> Result<(), Error> {
        let text_node_id = self.new_text(text);
        self.append(parent, text_node_id)?;
        Ok(())
    }

    /// Append an element node to a parent node given a name.
    ///
    /// Create a name id using [`Xot::add_name`] or [`Xot::add_name_ns`], or
    /// reuse an existing name id using [`Xot::name`], [`Xot::name_ns`].
    ///
    /// Example:
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    ///
    /// let root = xot.parse(r#"<doc></doc>"#)?;
    /// let doc_el = xot.document_element(root).unwrap();
    ///
    /// let name_id = xot.add_name("foo");
    /// xot.append_element(doc_el, name_id)?;
    ///
    /// assert_eq!(xot.to_string(root)?, "<doc><foo/></doc>");
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn append_element(&mut self, parent: Node, name_id: NameId) -> Result<(), Error> {
        let element_node_id = self.new_element(name_id);
        self.append(parent, element_node_id)?;
        Ok(())
    }

    /// Append a comment node to a parent node given comment text.
    pub fn append_comment(&mut self, parent: Node, comment: &str) -> Result<(), Error> {
        let comment_node_id = self.new_comment(comment);
        self.append(parent, comment_node_id)?;
        Ok(())
    }

    /// Append a processing instruction node to a parent node given target and data.
    pub fn append_processing_instruction(
        &mut self,
        parent: Node,
        target: NameId,
        data: Option<&str>,
    ) -> Result<(), Error> {
        let pi_node_id = self.new_processing_instruction(target, data);
        self.append(parent, pi_node_id)?;
        Ok(())
    }

    /// Prepend a child to the beginning of the children of the given parent.
    ///
    /// It is now the new first node of the parent.
    pub fn prepend(&mut self, parent: Node, child: Node) -> Result<(), Error> {
        self.add_structure_check(Some(parent), child)?;
        self.remove_consolidate_text_nodes(self.previous_sibling(child), self.next_sibling(child));
        if self.add_consolidate_text_nodes(child, None, self.first_child(parent)) {
            return Ok(());
        }
        // find the child to insert at; this is after the last namespace and attribute node
        let insertion_point = self
            .all_children(parent)
            .take_while(|node| self.value(*node).value_category() != ValueCategory::Normal)
            .last();
        if let Some(insertion_point) = insertion_point {
            insertion_point
                .get()
                .checked_insert_after(child.get(), self.arena_mut())?;
        } else {
            parent
                .get()
                .checked_prepend(child.get(), self.arena_mut())?;
        }

        Ok(())
    }

    /// Insert a new sibling after a reference node.
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc><a/><c/></doc>"#)?;
    ///
    /// let doc_el = xot.document_element(root)?;
    /// let a_el = xot.first_child(doc_el).unwrap();
    ///
    /// let b_name = xot.add_name("b");
    /// let b_el = xot.new_element(b_name);
    ///
    /// xot.insert_after(a_el, b_el)?;
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc><a/><b/><c/></doc>"#);
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn insert_after(&mut self, reference_node: Node, new_sibling: Node) -> Result<(), Error> {
        self.add_structure_check(self.parent(reference_node), new_sibling)?;
        self.remove_consolidate_text_nodes(
            self.previous_sibling(new_sibling),
            self.next_sibling(new_sibling),
        );
        if self.add_consolidate_text_nodes(
            new_sibling,
            Some(reference_node),
            self.next_sibling(reference_node),
        ) {
            return Ok(());
        }
        reference_node
            .get()
            .checked_insert_after(new_sibling.get(), self.arena_mut())?;
        Ok(())
    }

    /// Insert a new sibling before a reference node.
    pub fn insert_before(&mut self, reference_node: Node, new_sibling: Node) -> Result<(), Error> {
        self.add_structure_check(self.parent(reference_node), new_sibling)?;
        self.remove_consolidate_text_nodes(
            self.previous_sibling(new_sibling),
            self.next_sibling(new_sibling),
        );
        if self.add_consolidate_text_nodes(
            new_sibling,
            self.previous_sibling(reference_node),
            Some(reference_node),
        ) {
            return Ok(());
        }
        reference_node
            .get()
            .checked_insert_before(new_sibling.get(), self.arena_mut())?;
        Ok(())
    }

    /// Detach a node (and its descendants) from the tree.
    ///
    /// It now becomes an unattached tree (without top-level document node).
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc><a><b><c/></b></a></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    /// let a_el = xot.first_child(doc_el).unwrap();
    ///
    /// xot.detach(a_el)?;
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc/>"#);
    /// assert_eq!(xot.to_string(a_el)?, r#"<a><b><c/></b></a>"#);
    ///
    /// // a_al still exist; it's not removed like with [`Xot::remove`].
    /// assert!(!xot.is_removed(a_el));
    ///
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn detach(&mut self, node: Node) -> Result<(), Error> {
        let prev_node = self.previous_sibling(node);
        let next_node = self.next_sibling(node);
        node.get().detach(self.arena_mut());
        self.remove_consolidate_text_nodes(prev_node, next_node);
        Ok(())
    }

    /// Remove a node (and its descendants) from the tree
    ///
    /// This removes the nodes from Xot. Trying to access or
    /// manipulate a removed node results in a panic. You can verify
    /// that a node is removed by using [`Xot::is_removed`].
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc><a><b><c/></b></a></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    /// let a_el = xot.first_child(doc_el).unwrap();
    ///
    /// xot.remove(a_el)?;
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc/>"#);
    ///
    /// // a_al is removed; it's not detached like with [`Xot::detach`].
    /// assert!(xot.is_removed(a_el));
    ///
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn remove(&mut self, node: Node) -> Result<(), Error> {
        let prev_node = self.previous_sibling(node);
        let next_node = self.next_sibling(node);
        node.get().remove_subtree(self.arena_mut());
        self.remove_consolidate_text_nodes(prev_node, next_node);
        Ok(())
    }

    /// Set the element name of a node.
    ///
    /// If this node is not an element, panic.
    pub fn set_element_name(&mut self, node: Node, name_id: NameId) {
        match self.value_mut(node) {
            Value::Element(element) => {
                element.set_name(name_id);
            }
            _ => panic!("Node is not an element, so cannot set element name"),
        }
    }

    /// Mutable namespaces accessor.
    ///
    /// Panics if called on a non-element.
    ///
    /// Use this to set namespace prefix declarations on an element. You use a
    /// hashmap-like API:
    ///
    /// ```rust
    /// let mut xot = xot::Xot::new();
    /// let foo_prefix = xot.add_prefix("foo");
    /// let foo_ns = xot.add_namespace("FOO");
    /// let root = xot.parse(r#"<p>Example</p>"#).unwrap();
    /// let p = xot.document_element(root).unwrap();
    /// let mut namespaces = xot.namespaces_mut(p);
    /// namespaces.insert(foo_prefix, foo_ns);
    ///
    /// assert_eq!(xot.to_string(root).unwrap(), r#"<p xmlns:foo="FOO">Example</p>"#);
    /// ```
    pub fn namespaces_mut(&mut self, node: Node) -> MutableNamespaces {
        if !self.is_element(node) {
            panic!("Node is not an element, so cannot set namespaces");
        }

        MutableNamespaces::new(self, node)
    }

    /// Set namespace for a prefix on an element.
    ///
    /// Note that if this is invoked on a non-element it's going to panic.
    pub fn set_namespace(&mut self, node: Node, prefix: PrefixId, ns: NamespaceId) {
        self.namespaces_mut(node).insert(prefix, ns);
    }

    /// Remove namespace for an element, if it exists
    ///
    /// Note that if this is invoked on a non-element it's going to panic.
    pub fn remove_namespace(&mut self, node: Node, prefix: PrefixId) {
        self.namespaces_mut(node).remove(prefix);
    }

    /// Mutable attributes accessor
    ///
    /// Panics if called on a non-element.
    ///
    /// Use this if you want to set an attribute on an element. You use a
    /// hashmap-like API:
    ///
    /// ```rust
    /// let mut xot = xot::Xot::new();
    /// let a = xot.add_name("a");
    /// let root = xot.parse(r#"<p>Example</p>"#).unwrap();
    /// let p = xot.document_element(root).unwrap();
    /// let mut attributes = xot.attributes_mut(p);
    /// attributes.insert(a, "A".to_string());
    ///
    /// assert_eq!(xot.to_string(root).unwrap(), r#"<p a="A">Example</p>"#);
    /// ```
    pub fn attributes_mut(&mut self, node: Node) -> MutableAttributes {
        if !self.is_element(node) {
            panic!("Node is not an element, so cannot set attributes");
        }
        MutableAttributes::new(self, node)
    }

    /// Set attribute on an element.
    ///
    /// Note that if this is invoked on a non-element it's going to panic.
    pub fn set_attribute(&mut self, node: Node, name: NameId, value: impl Into<String>) {
        self.attributes_mut(node).insert(name, value.into());
    }

    /// Remove attribute from an element, if it exists
    ///
    /// Note that if this is invoked on a non-element it's going to panic.
    pub fn remove_attribute(&mut self, node: Node, name: NameId) {
        self.attributes_mut(node).remove(name);
    }

    /// Clone a node and its descendants into a new unattached tree.
    ///
    /// The cloned nodes are not attached to anything. If you clone a document
    /// node, you clone the whole document (or fragment).
    ///
    /// This does not include any namespace prefix information defined in any
    /// ancestors of the cloned node. If you want to preserve such prefix
    /// information, see [`Xot::clone_with_prefixes`].
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc><a f="F"><b><c/></b></a></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    /// let a_el = xot.first_child(doc_el).unwrap();
    ///
    /// let cloned = xot.clone_node(a_el);
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc><a f="F"><b><c/></b></a></doc>"#);
    ///
    /// // cloned is not attached to anything
    /// assert!(xot.parent(cloned).is_none());
    ///
    /// // cloned is a new unattached tree which you can serialize
    /// assert_eq!(xot.to_string(cloned)?, r#"<a f="F"><b><c/></b></a>"#);
    ///
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn clone_node(&mut self, node: Node) -> Node {
        let value = self.value(node);

        let top = match value {
            // if it's nested content, we create a new top element
            Value::Document => self.new_document(),
            // this is really an outer dummy element, reusing the name
            Value::Element(element) => self.new_element(element.name()),
            // if it's not a nested value, simply clone the contents
            _ => {
                return self.new_node(value.clone());
            }
        };

        let edges = self.all_traverse(node).collect::<Vec<_>>();

        let mut current = top;
        for open_close in edges {
            match open_close {
                NodeEdge::Start(node) => {
                    let value = self.value(node);
                    let value_type = value.value_type();
                    if value_type == ValueType::Document {
                        continue;
                    }
                    let new_node = self.new_node(value.clone());
                    self.any_append(current, new_node).unwrap();
                    if value_type == ValueType::Element {
                        current = new_node;
                    }
                }
                NodeEdge::End(node) => {
                    if self.value_type(node) != ValueType::Element {
                        continue;
                    }
                    current = self.parent(current).unwrap();
                }
            }
        }

        if self.is_element(top) {
            // remove the temporary element
            let cloned_node = self.first_child(top).unwrap();
            // we can remove it as it won't have any attributes or prefixes
            self.remove_dangerously(top);
            cloned_node
        } else {
            // it's a document
            top
        }
    }

    /// Clone a node and its descendants into a new unattached tree.
    ///
    /// If the cloned node is an element, required namespace prefixes that are
    /// in scope are added to the cloned node. Only those namespaces that
    /// are in fact in use in the node or descendants are added.
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc xmlns:foo="http://example.com"><foo:a><foo:b><foo:c/></foo:b></foo:a></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    /// let a_el = xot.first_child(doc_el).unwrap();
    ///
    /// let cloned = xot.clone_with_prefixes(a_el);
    /// assert_eq!(xot.to_string(cloned)?, r#"<foo:a xmlns:foo="http://example.com"><foo:b><foo:c/></foo:b></foo:a>"#);
    ///
    /// // if you do a normal clone, prefixes aren't preserved and need to be generated instead
    ///
    /// let cloned = xot.clone_node(a_el);
    /// xot.create_missing_prefixes(cloned)?;
    /// assert_eq!(xot.to_string(cloned)?, r#"<n0:a xmlns:n0="http://example.com"><n0:b><n0:c/></n0:b></n0:a>"#);
    ///
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn clone_with_prefixes(&mut self, node: Node) -> Node {
        // get all prefixes defined in scope
        let prefixes = self.inherited_prefixes(node);

        let clone = self.clone_node(node);
        // add any prefixes from outer scope we may need
        if self.is_element(clone) {
            let mut namespaces = self.namespaces_mut(clone);
            for (prefix, ns) in prefixes {
                if namespaces.contains_key(prefix) {
                    continue;
                }
                namespaces.insert(prefix, ns);
            }
        }
        clone
    }

    // removes a node and puts normal content into containing node.
    // any non-normal content (i.e. attributes and namespaces) are really
    // destroyed
    fn remove_element(&mut self, node: Node) {
        // first remove any abnormal children, if any
        for abnormal_child in self.abnormal_children(node).collect::<Vec<_>>() {
            self.remove_dangerously(abnormal_child);
        }
        // now remove the node itself. this is now safe and won't result in
        // stray nodes
        self.remove_dangerously(node);
    }

    // remove a non-element node or an element guaranteed to be without
    // prefixes or attributes with this.
    fn remove_dangerously(&mut self, node: Node) {
        // remove the node itself
        node.get().remove(self.arena_mut());
    }

    /// Unwrap an element; its children are moved to its parent.
    ///
    /// The unwrapped element itself is removed.
    ///
    /// You can unwrap the document element, but only if that document
    /// has exactly 1 child that is an element.
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    ///
    /// let root = xot.parse(r#"<doc><a><b><c/></b></a></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    /// let a_el = xot.first_child(doc_el).unwrap();
    ///
    /// xot.element_unwrap(a_el)?;
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc><b><c/></b></doc>"#);
    ///
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn element_unwrap(&mut self, node: Node) -> Result<(), Error> {
        if !self.is_element(node) {
            return Err(Error::InvalidOperation(
                "Cannot unwrap non-element nodes".to_string(),
            ));
        }

        let first_child = self.first_child(node);
        // without children this is like a remove
        if first_child.is_none() {
            return self.remove(node);
        }
        let first_child = first_child.unwrap();
        // there is guaranteed to be a last child if there's a first child
        let last_child = self.last_child(node).unwrap();
        self.remove_element(node);

        let prev_node = self.previous_sibling(first_child);
        let next_node = self.next_sibling(last_child);
        if self.remove_consolidate_text_nodes(prev_node, Some(first_child)) {
            // if first child got consolidated
            if first_child == last_child {
                // if there was only a single child, try to consolidate prev_node with
                // next sibling of last child
                self.remove_consolidate_text_nodes(prev_node, next_node);
            } else {
                // otherwise consolidate last child with next sibling
                self.remove_consolidate_text_nodes(Some(last_child), self.next_sibling(last_child));
            }
        } else {
            // first child did not get consolidated
            self.remove_consolidate_text_nodes(Some(last_child), self.next_sibling(last_child));
        }
        Ok(())
    }

    /// Wrap a node in a new element
    ///
    /// Returns the node for the new wrapping element.
    ///
    /// It's not allowed to wrap the document node. It's allowed to wrap the
    /// document element but not any comment or processing instruction nodes
    /// directly under the document.
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    /// let root = xot.parse(r#"<doc><b><c/></b></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    /// let b_el = xot.first_child(doc_el).unwrap();
    ///
    /// let a_name = xot.add_name("a");
    /// let wrapper = xot.element_wrap(b_el, a_name)?;
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc><a><b><c/></b></a></doc>"#);
    /// assert_eq!(xot.to_string(wrapper)?, r#"<a><b><c/></b></a>"#);
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn element_wrap(&mut self, node: Node, name_id: NameId) -> Result<Node, Error> {
        if self.is_document(node) {
            return Err(Error::InvalidOperation(
                "Cannot wrap document node".to_string(),
            ));
        }
        // we forbid wrapping nodes under the document node too unless it's the
        // document element
        if self.has_document_parent(node) && !self.is_document_element(node) {
            return Err(Error::InvalidOperation(
                "Cannot wrap nodes under document node except document element".to_string(),
            ));
        }

        if let Some(parent) = self.parent(node) {
            // record previous sibling
            let previous_node = self.previous_sibling(node);
            // create new element
            let wrapper = self.new_element(name_id);
            // detach the node, use low-level detach as we don't want to consolidate
            // text nodes
            node.get().detach(self.arena_mut());
            // append the node to the wrapper
            self.append(wrapper, node)?;
            // now insert the wrapper element
            if let Some(previous_node) = previous_node {
                self.insert_after(previous_node, wrapper)?;
            } else {
                self.prepend(parent, wrapper)?;
            }
            Ok(wrapper)
        } else {
            // we have no parent, standalone node
            let wrapper = self.new_element(name_id);
            self.append(wrapper, node)?;
            Ok(wrapper)
        }
    }

    /// Replace a node with another one.
    ///
    /// The replaced node and all its descendants are removed.
    ///
    /// This works for any node, except the document node itself.
    ///
    /// ```rust
    /// use xot::Xot;
    ///
    /// let mut xot = Xot::new();
    ///
    /// let root = xot.parse(r#"<doc><a><b/></a><c/></doc>"#)?;
    /// let doc_el = xot.document_element(root)?;
    /// let a_el = xot.first_child(doc_el).unwrap();
    ///
    /// let d_name = xot.add_name("d");
    /// let d_el = xot.new_element(d_name);
    ///
    /// xot.replace(a_el, d_el)?;
    ///
    /// assert_eq!(xot.to_string(root)?, r#"<doc><d/><c/></doc>"#);
    /// # Ok::<(), xot::Error>(())
    /// ```
    pub fn replace(&mut self, replaced_node: Node, replacing_node: Node) -> Result<(), Error> {
        if self.is_document(replaced_node) {
            return Err(Error::InvalidOperation(
                "Cannot replace document node".to_string(),
            ));
        }
        // there should always be a parent as we're not document node
        let parent = self.parent(replaced_node).unwrap();
        // record previous sibling
        let previous_node = self.previous_sibling(replaced_node);
        // remove the replaced node, use low-level remove_tree to avoid
        // text node reconciliation and document element detection
        replaced_node.get().remove_subtree(self.arena_mut());
        // now insert the replacing node
        if let Some(previous_node) = previous_node {
            self.insert_after(previous_node, replacing_node)?;
        } else {
            self.prepend(parent, replacing_node)?;
        }
        Ok(())
    }

    /// Set text consolidation
    ///
    /// By default, text nodes are consolidated when possible. You can turn
    /// off this behavior so text nodes are never merged by calling this.
    pub fn set_text_consolidation(&mut self, consolidate: bool) {
        self.text_consolidation = consolidate;
    }

    fn add_structure_check(&self, parent: Option<Node>, child: Node) -> Result<(), Error> {
        let parent = parent.ok_or_else(|| {
            Error::InvalidOperation("Cannot create siblings for document node".into())
        })?;
        if !matches!(
            self.value_type(parent),
            ValueType::Element | ValueType::Document
        ) {
            return Err(Error::InvalidOperation(
                "Cannot add children to non-element and non-document node".into(),
            ));
        }
        match self.value_type(child) {
            ValueType::Document => {
                return Err(Error::InvalidOperation("Cannot move document node".into()));
            }
            ValueType::Element => {
                // we are allowed to move an element under the document node,
                // though only in a fragment
            }
            ValueType::Text => {
                // we are allowed to move text under the document node,
                // though only in a fragment
            }
            ValueType::ProcessingInstruction | ValueType::Comment => {
                // these can exist everywhere
            }
            ValueType::Attribute | ValueType::Namespace => {
                return Err(Error::InvalidOperation(
                    "Cannot move attribute or namespace under element as normal child".into(),
                ));
            }
        }
        Ok(())
    }

    /// Remove insignificant whitespace
    ///
    /// XML officially does not have a notion of insignificant whitespace, but
    /// here we employ the following one: a text node can be removed if
    /// it contains only whitespace and has no text sibling that contains
    /// non-whitespace text.
    pub fn remove_insignificant_whitespace(&mut self, node: Node) {
        remove_insignificant_whitespace(self, node);
    }

    fn add_consolidate_text_nodes(
        &mut self,
        node: Node,
        prev_node: Option<Node>,
        next_node: Option<Node>,
    ) -> bool {
        if !self.text_consolidation {
            return false;
        }
        let added_text = if let Value::Text(t) = self.value(node) {
            Some(t.get().to_string())
        } else {
            None
        };
        if added_text.is_none() {
            return false;
        }
        let added_text = added_text.unwrap();

        // if consolidation is turned off, then we could have two adjacent
        // text nodes. Prefer to consolidate with the previous node.
        let consolidated = if let Some(prev_node) = prev_node {
            if let Value::Text(prev) = self.value_mut(prev_node) {
                let mut s = prev.get().to_string();
                s.push_str(&added_text);
                prev.set(s);
                // remove the text node we wanted to insert as it's now consolidated
                // we can always remove text nodes safely.
                self.remove_dangerously(node);
                true
            } else {
                false
            }
        } else {
            false
        };
        if consolidated {
            return true;
        }
        // we couldn't consolidate with the previous node, try to consolidate
        // with the next node
        if let Some(next_node) = next_node {
            if let Value::Text(next) = self.value_mut(next_node) {
                let mut s = added_text;
                s.push_str(next.get());
                next.set(s);
                // remove the text node we wanted to insert as it's now consolidated
                // we can always remove text nodes safely.
                self.remove_dangerously(node);
                true
            } else {
                false
            }
        } else {
            false
        }
    }

    fn remove_consolidate_text_nodes(
        &mut self,
        prev_node: Option<Node>,
        next_node: Option<Node>,
    ) -> bool {
        if !self.text_consolidation {
            return false;
        }
        if prev_node.is_none() {
            return false;
        }
        let prev_node = prev_node.unwrap();
        if next_node.is_none() {
            return false;
        }
        let next_node = next_node.unwrap();
        let prev_text = self.text(prev_node);
        let next_text = self.text(next_node);
        if prev_text.is_none() || next_text.is_none() {
            return false;
        }
        let to_add = next_text.unwrap().get().to_string();

        let prev_text_mut = self.text_mut(prev_node).unwrap();
        let mut s = prev_text_mut.get().to_string();
        s.push_str(&to_add);
        prev_text_mut.set(s);
        // this is guaranteed to be a text node
        self.remove_dangerously(next_node);
        true
    }
}