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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
/*!
# Simple XML Serialization
This is a Rust crate for serialization of data to XML. `XMLElement`s can either be built
manually, or the `simple_xml_serialize_macro` crate can be used to generate `From` implementations for structs. 

## Example Usage
```rust
use simple_xml_serialize::XMLElement;

fn main() {
    // build up your XMLElement with individual calls ...
    let mut ele = XMLElement::new("person");
    ele.add_attr("age", 28); // accept any value that implements `ToString`.
    ele.set_text("John Doe");

    // ... or with the builder pattern
    let sub_ele = XMLElement::new("person")
        .attr("age", 4)
        .text("Jane Doe");

    ele.add_element(sub_ele); // `add_element` accepts values that implement `Into<XMLElement>`

    let expected = r#"<person age="28"><person age="4">Jane Doe</person>John Doe</person>"#;
    assert_eq!(expected, ele.to_string());
    println!("{}",  ele.to_string_pretty("\n", "\t")); // specify your preferred newline and indentation for pretty printing

    ele.set_text("John Doe > John Deere"); // illegal characters in text will be substituted e.g. > becomes &gt;
    let expected = r#"<person age="28"><person age="4">Jane Doe</person>John Doe &gt; John Deere</person>"#;
    assert_eq!(expected, ele.to_string());

   
    ele.set_text("<![CDATA[John Doe > John Deere]]>"); // illegal characters in CDATA tags are respected
    let expected = r#"<person age="28"><person age="4">Jane Doe</person><![CDATA[John Doe > John Deere]]></person>"#;
    assert_eq!(expected, ele.to_string());
}
```
*/

use std::fmt;

/// The basic type this crate provides. Functions are provided for setting/adding to the fields in this struct.
/// Any manipulation past that is left to the user by accessing the fields directly.
#[derive(Clone,PartialEq,Debug)]
pub struct XMLElement {
    /// The tag for this element node. IE `<myelement/>`
    pub name: String,
    /// Nested XMLElements. IE `<myelement><nested/></myelement>`
    pub contents: Option<Vec<XMLElement>>,
    /// Plain character data inside of the node. IE `<myelement>hello world</myelement>`
    pub text: Option<String>,
    /// The key/value pairs inside of an element tag. IE `<myelement attr1="hello" attr2="world"/>`
    pub attrs: Option<Vec<XMLAttr>>,

    /// Allows for writing raw string contents that won't have special characters replaced. Useful for 
    /// including already properly formed xml without it having to be an XMLElement. Placed after 'contents' and before 'text'
    pub raw: Option<String>,
}

impl fmt::Display for XMLElement {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut ret = String::new();
        ret.push('<');
        ret.push_str(&self.name);
        
        if let Some(ref attrs) = self.attrs {
            for a in attrs {
                ret.push(' ');
                ret.push_str(&a.name);
                ret.push('=');
                ret.push('"');
                ret.push_str(&a.value);
                ret.push('"');
            }
        }
        if self.contents.is_none() && self.text.is_none() && self.raw.is_none() {
            ret.push('/');
            ret.push('>');
        } else {
            ret.push('>');

            if let Some(contents) = &self.contents {
                for c in contents {
                    ret.push_str(&c.to_string());
                }
            }
            if let Some(ref raw_string) = &self.raw {
                ret.push_str(raw_string);
            }
            if let Some(text) = &self.text {
                let (before_cdata, opt_cdata) = split_cdata(&text);
                let text = before_cdata.replace("&", "&amp;");
                let text = text.replace("<", "&lt;");
                let text = text.replace(">", "&gt;");
                let text = text.replace("'", "&apos;");
                let text = text.replace(r#"""#, "&quot;");
                ret.push_str(&text);
                if let Some((cdata, after_cdata)) = opt_cdata {
                    ret.push_str(&cdata);
                    let text = after_cdata.replace("&", "&amp;");
                    let text = text.replace("<", "&lt;");
                    let text = text.replace(">", "&gt;");
                    let text = text.replace("'", "&apos;");
                    let text = text.replace(r#"""#, "&quot;");
                    ret.push_str(&text);
                }
            }

            ret.push_str(&format!("</{}>", self.name));
        }
        write!(f, "{}", ret)
    }
}


fn split_cdata(text: &str) -> (String, Option<(String, String)>) {
    let cdata_start = "<![CDATA[";
    let cdata_end = "]]>";
    let csi = match text.find(&cdata_start) {
        None => {return (text.to_string(), None)},
        Some(index) => index,
    };
    let cei = match text[csi..].find(&cdata_end) {
        None => {return (text.to_string(), None)},
        Some(index) => csi+index+3,
    };
    let before_cdata = String::from(&text[..csi]);
    let cdata_section = String::from(&text[csi..cei]);
    let after_cdata = String::from(&text[cei..]);
    return (before_cdata, Some((cdata_section, after_cdata)));
}

impl From<&XMLElement> for XMLElement {
    fn from(e: &XMLElement) -> Self {
        e.clone()
    }
}

impl XMLElement {

    /// Constructs a new XMLElement with the given name and `None` for the rest of the fields
    /// # Arguments
    /// 
    /// * `name` - A string slice that holds the name of the XML element displayed at the element root
    ///
    /// # Example
    ///
    /// ```
    /// use simple_xml_serialize::XMLElement;
    /// let ele = XMLElement::new("name");
    /// assert_eq!(ele.to_string(), String::from("<name/>"));
    /// ```
    pub fn new(name: &str) -> Self {
        XMLElement{
            name: String::from(name),
            contents: None,
            attrs: None,
            text: None,
            raw: None,
        }
    }

    /// Builder pattern function for changing the name of an XMLElement
    /// # Arguments
    /// 
    /// * `name` - A string slice that holds the name of the XML element displayed at the element root
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// let ele = XMLElement::new("name").name("changed");
    /// assert_eq!(ele.to_string(), String::from("<changed/>"));
    /// ```
    pub fn name(mut self, name: &str) -> Self {
        self.set_name(name);
        self
    }

    /// Changes the name of an XMLElement
    /// # Arguments
    /// 
    /// * `name` - A string slice that holds the name of the XML element displayed at the element root
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// let mut ele = XMLElement::new("name");
    /// ele.set_name("changed");
    /// assert_eq!(ele.to_string(), String::from("<changed/>"));
    /// ```
    pub fn set_name(&mut self, name: &str) {
        self.name = String::from(name);
    }

    /// Builder pattern function for adding an attribute to the XMLElement
    /// # Arguments
    /// 
    /// * `attr` - A string slice that holds the name of the attribute
    /// * `attr_val` - Any type that implements ToString; the value of the attribute
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// let ele = XMLElement::new("name").attr("my_attr", 1);
    /// assert_eq!(ele.to_string(), String::from(r#"<name my_attr="1"/>"#));
    /// ```
    pub fn attr(mut self, attr: &str, attr_val: impl ToString) -> Self {
        self.add_attr(attr, attr_val);
        self
    }

    /// Adds an attribute to the XMLElement
    /// # Arguments
    /// 
    /// * `attr` - A string slice that holds the name of the attribute
    /// * `attr_val` - Any type that implements ToString; the value of the attribute
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// let mut ele = XMLElement::new("name");
    /// ele.add_attr("my_attr", 1);
    /// assert_eq!(ele.to_string(), String::from(r#"<name my_attr="1"/>"#));
    /// ```
    pub fn add_attr(&mut self, attr: &str, attr_val: impl ToString) {
        if let Some(ref mut attr_vec) = self.attrs {
            let new_attr: XMLAttr = XMLAttr{
                name: String::from(attr),
                value: attr_val.to_string(),
            };
            attr_vec.push(new_attr);
        } else {
            let mut attr_vec: Vec<XMLAttr> = Vec::new();
            let new_attr: XMLAttr = XMLAttr{
                name: String::from(attr),
                value: attr_val.to_string(),
            };
            attr_vec.push(new_attr);
            self.attrs = Some(attr_vec);
        }
    }

    /// Builder pattern function for adding an element to the contents of this XMLElement
    /// # Arguments
    /// 
    /// * `new_ele` - Any type that implements `Into<XMLElement>`
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// struct MyPoint {}
    /// impl From<MyPoint> for XMLElement {
    ///     fn from(p: MyPoint) -> Self {
    ///         XMLElement::new("point")
    ///     }
    /// }
    /// let ele = XMLElement::new("name").element(MyPoint{});
    /// assert_eq!(ele.to_string(), String::from("<name><point/></name>"));
    /// ```
    pub fn element(mut self, new_ele: impl Into<XMLElement>) -> Self {
        self.add_element(new_ele.into());
        self
    }

    /// Adds an element to the contents of this XMLElement
    /// # Arguments
    /// 
    /// * `new_ele` - Any type that implements `Into<XMLElement>`
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// # struct MyPoint {}
    /// # impl From<MyPoint> for XMLElement {
    /// #     fn from(p: MyPoint) -> Self {
    /// #         XMLElement::new("point")
    /// #     }
    /// # }
    /// let mut ele = XMLElement::new("name");
    /// ele.add_element(MyPoint{});
    /// assert_eq!(ele.to_string(), String::from("<name><point/></name>"));
    /// ```
    pub fn add_element(&mut self, new_ele: impl Into<XMLElement>) {
        if let Some(ref mut ele_vec) = self.contents {
            ele_vec.push(new_ele.into());
        } else {
            let mut ele_vec: Vec<XMLElement> = Vec::new();
            ele_vec.push(new_ele.into());
            self.contents = Some(ele_vec);
        }
    }

    /// Builder pattern for adding a collection of elements to the contents of this XMLElement
    /// # Arguments
    /// 
    /// * `new_eles` - Any collection of `Into<XMLElement>` as long as that collection implements `IntoIterator`
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// # struct MyPoint {}
    /// # impl From<MyPoint> for XMLElement {
    /// #     fn from(p: MyPoint) -> Self {
    /// #         XMLElement::new("point")
    /// #     }
    /// # }
    /// let points: Vec<MyPoint> = vec![MyPoint{}, MyPoint{}];
    /// let mut ele = XMLElement::new("name").elements(points);
    /// assert_eq!(ele.to_string(), String::from("<name><point/><point/></name>"));
    /// ```
    pub fn elements<T>(mut self, new_eles: T) -> Self 
        where T: IntoIterator, T::Item : Into<XMLElement>,
    {
        self.add_elements(new_eles);
        self
    }

    /// Adds a collection of elements to the contents of this XMLElement
    /// # Arguments
    /// 
    /// * `new_eles` - Any collection of `Into<XMLElement>` as long as that collection implements `IntoIterator`
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// # struct MyPoint {}
    /// # impl From<MyPoint> for XMLElement {
    /// #     fn from(p: MyPoint) -> Self {
    /// #         XMLElement::new("point")
    /// #     }
    /// # }
    /// let points: Vec<MyPoint> = vec![MyPoint{}, MyPoint{}];
    /// let mut ele = XMLElement::new("name");
    /// ele.add_elements(points);
    /// assert_eq!(ele.to_string(), String::from("<name><point/><point/></name>"));
    /// ```
    pub fn add_elements<T>(&mut self, new_eles: T) 
        where T: IntoIterator, T::Item : Into<XMLElement>,
    {
        for ele in new_eles.into_iter() {
            self.add_element(ele);
        }
    }

    /// Adds a collection of elements to the contents of this XMLElement and changes the element name of each
    /// # Arguments
    /// 
    /// * `new_name` - A string slice containing the name to use when adding the elements
    /// * `new_eles` - Any collection of `Into<XMLElement>` as long as that collection implements `IntoIterator`
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// # struct MyPoint {}
    /// # impl From<MyPoint> for XMLElement {
    /// #     fn from(p: MyPoint) -> Self {
    /// #         XMLElement::new("point")
    /// #     }
    /// # }
    /// let mut ele = XMLElement::new("name");
    /// let points: Vec<MyPoint> = vec![MyPoint{}, MyPoint{}];
    /// ele.add_elements_with_name("p", points);
    /// assert_eq!(ele.to_string(), String::from("<name><p/><p/></name>"));
    /// ```
    pub fn add_elements_with_name<T>(&mut self, new_name: &str, new_eles: T) 
        where T: IntoIterator, T::Item : Into<XMLElement>,
    {
        for ele in new_eles.into_iter() {
            let new_element: XMLElement = ele.into();
            self.add_element(new_element.name(new_name));
        }
    }

    /// Builder pattern function for adding raw content to the XMLElement.
    /// In the ToString implementation for XMLElement, raw content is placed after normal contents and before text.
    /// # Arguments
    /// 
    /// * `raw` - Any type that implements ToString; content in the element
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// let ele = XMLElement::new("name").raw("<raw_content>Some content</raw_content>");
    /// assert_eq!(ele.to_string(), String::from("<name><raw_content>Some content</raw_content></name>"));
    /// ```
    pub fn raw(mut self, raw: impl ToString) -> Self {
        self.set_raw(raw);
        self
    }

    /// Adds raw text to the contents of the XMLElement. In the ToString implementation for
    /// XMLElement, raw content is placed after normal contents and before text.
    /// # Arguments
    /// 
    /// * `text` - Any type that implements ToString; text in the element
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// let mut ele = XMLElement::new("name");
    /// ele.set_raw("<raw_content>Some content</raw_content>");
    /// assert_eq!(ele.to_string(), String::from("<name><raw_content>Some content</raw_content></name>"));
    /// ```
    pub fn set_raw(&mut self, raw: impl ToString) {
        self.raw = Some(raw.to_string());
    }

    /// Builder pattern function for adding raw text to the contents of the XMLElement.
    /// In the ToString implementation for XMLElement, raw text is always placed after all other contents.
    /// # Arguments
    /// 
    /// * `text` - Any type that implements ToString; text in the element
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// let ele = XMLElement::new("name").text("Some content");
    /// assert_eq!(ele.to_string(), String::from("<name>Some content</name>"));
    /// ```
    pub fn text(mut self, text: impl ToString) -> Self {
        self.set_text(text);
        self
    }

    /// Adds raw text to the contents of the XMLElement. In the ToString implementation for
    /// XMLElement, raw text is always placed after all other contents.
    /// # Arguments
    /// 
    /// * `text` - Any type that implements ToString; text in the element
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// let mut ele = XMLElement::new("name");
    /// ele.set_text("Some content");
    /// assert_eq!(ele.to_string(), String::from("<name>Some content</name>"));
    /// ```
    pub fn set_text(&mut self, text: impl ToString) {
        self.text = Some(text.to_string());
    }

    /// Returns the string representation of the XMLElement, but with newlines and the given indentation
    /// # Arguments
    /// 
    /// * `indent` - A string slice containing the characters to use to indent the document
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// # struct MyPoint {}
    /// # impl From<MyPoint> for XMLElement {
    /// #     fn from(p: MyPoint) -> Self {
    /// #         XMLElement::new("point")
    /// #     }
    /// # }
    /// let mut ele = XMLElement::new("name");
    /// ele.set_text("Some content");
    /// ele.add_element(MyPoint{});
    /// let expected = String::from(r#"<name>
    ///   <point/>
    ///   Some content
    /// </name>"#);
    /// assert_eq!(ele.to_string_pretty("\n", "  "), expected);
    /// ```
    pub fn to_string_pretty(&self, newline: &str, indent: &str) -> String {
        let mut ret = String::new();
        ret.push('<');
        ret.push_str(&self.name);
        
        if let Some(ref attrs) = self.attrs {
            for a in attrs {
                ret.push(' ');
                ret.push_str(&a.name);
                ret.push('=');
                ret.push('"');
                ret.push_str(&a.value);
                ret.push('"');
            }
        }
        if self.contents.is_none() && self.text.is_none() {
            ret.push('/');
            ret.push('>');
        } else {
            ret.push('>');

            let mut intermediate_ret = String::new();

            if let Some(contents) = &self.contents {
                for c in contents {
                    intermediate_ret.push_str(&c.to_string_pretty(newline, indent));
                    intermediate_ret.push_str(newline);
                }
            }
            if let Some(raw_contents) = &self.raw {
                intermediate_ret.push_str(raw_contents);
            }
            if let Some(text) = &self.text {
                let (before_cdata, opt_cdata) = split_cdata(&text);
                let text = before_cdata.replace("&", "&amp;");
                let text = text.replace("<", "&lt;");
                let text = text.replace(">", "&gt;");
                let text = text.replace("'", "&apos;");
                let text = text.replace(r#"""#, "&quot;");
                intermediate_ret.push_str(&text);
                if let Some((cdata, after_cdata)) = opt_cdata {
                    intermediate_ret.push_str(&cdata);
                    let text = after_cdata.replace("&", "&amp;");
                    let text = text.replace("<", "&lt;");
                    let text = text.replace(">", "&gt;");
                    let text = text.replace("'", "&apos;");
                    let text = text.replace(r#"""#, "&quot;");
                    intermediate_ret.push_str(&text);
                }
            }
            for l in intermediate_ret.lines() {
                ret.push_str(newline);
                ret.push_str(indent);
                ret.push_str(l);
            }
            ret.push_str(newline);
            ret.push_str(&format!("</{}>", self.name));
        }
        
        ret
    }

    /// Returns the string representation of the XMLElement, but with newlines and the given indentation and an xml prolog
    /// # Arguments
    /// 
    /// * `indent` - A string slice containing the characters to use to indent the document
    ///
    /// # Example
    ///
    /// ```
    /// # use simple_xml_serialize::XMLElement;
    /// # struct MyPoint {}
    /// # impl From<MyPoint> for XMLElement {
    /// #     fn from(p: MyPoint) -> Self {
    /// #         XMLElement::new("point")
    /// #     }
    /// # }
    /// let mut ele = XMLElement::new("name");
    /// ele.set_text("Some content");
    /// ele.add_element(MyPoint{});
    /// let expected = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>
    /// <name>
    ///   <point/>
    ///   Some content
    /// </name>"#);
    /// assert_eq!(ele.to_string_pretty_prolog("\n", "  "), expected);
    /// ```
    pub fn to_string_pretty_prolog(&self, newline: &str, indent: &str) -> String {
        let mut ret = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
        ret.push_str(newline);
        ret.push_str(&self.to_string_pretty(newline, indent));
        ret
    }
}

/// A key/value pair that is serialized inside the opening tag of an XMLElement.
#[derive(Clone,PartialEq,Debug)]
pub struct XMLAttr {
    pub name: String,
    pub value: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn xmlelement_eq() {
        let ele1 = XMLElement::new("test_element");
        let mut ele2 = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
        ele2.text = Some(String::from("hey"));
        assert_ne!(ele1, ele2);
    }

    #[test]
    fn xmlelement_new() {
        let newele = XMLElement::new("test_element");
        let testele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(newele, testele);
    }


    #[test]
    fn xmlelement_name() {
        let ele1 = XMLElement::new("test_element").name("new_name");
        let ele2 = XMLElement{
            name: String::from("new_name"),
            contents: None,
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_set_name() {
        let mut ele1 = XMLElement::new("test_element");
        ele1.set_name("new_name");
        let ele2 = XMLElement{
            name: String::from("new_name"),
            contents: None,
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }


    #[test]
    fn xmlelement_attr() {
        let ele1 = XMLElement::new("test_element").attr("a1", 42);
        let test_attr = XMLAttr{name: String::from("a1"), value: 42.to_string()};
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: None,
            attrs: Some(vec![test_attr]),
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_add_attr() {
        let mut ele1 = XMLElement::new("test_element");
        ele1.add_attr("a1", 42);
        let test_attr = XMLAttr{name: String::from("a1"), value: 42.to_string()};
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: None,
            attrs: Some(vec![test_attr]),
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    struct Point {
        lat: f32,
        lon: f32,
    }

    impl From<Point> for XMLElement {
        fn from(p: Point) -> Self {
            XMLElement::new("point").attr("lat", p.lat).attr("lon", p.lon)
        }
    }



    #[test]
    fn xmlelement_element() {
        let ele1 = XMLElement::new("test_element").element(Point{lat: 12.3, lon: 45.6});
        
        let point_ele: XMLElement = Point{lat: 12.3, lon: 45.6}.into();
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: Some(vec![point_ele]),
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_add_element() {
        let mut ele1 = XMLElement::new("test_element");
        ele1.add_element(Point{lat: 12.3, lon: 45.6});
        
        let point_ele: XMLElement = Point{lat: 12.3, lon: 45.6}.into();
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: Some(vec![point_ele]),
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_elements() {
        let ele_vec = vec![Point{lat: 12.3, lon: 45.6}, Point{lat: 32.1, lon: 65.4}];
        let ele1 = XMLElement::new("test_element").elements(ele_vec);
        
        let point_ele1: XMLElement = Point{lat: 12.3, lon: 45.6}.into();
        let point_ele2: XMLElement = Point{lat: 32.1, lon: 65.4}.into();
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: Some(vec![point_ele1, point_ele2]),
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_add_elements() {
        let ele_vec = vec![Point{lat: 12.3, lon: 45.6}, Point{lat: 32.1, lon: 65.4}];
        let mut ele1 = XMLElement::new("test_element");
        ele1.add_elements(ele_vec);
        
        let point_ele1: XMLElement = Point{lat: 12.3, lon: 45.6}.into();
        let point_ele2: XMLElement = Point{lat: 32.1, lon: 65.4}.into();
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: Some(vec![point_ele1, point_ele2]),
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_add_elements_with_name() {
        let ele_vec = vec![Point{lat: 12.3, lon: 45.6}, Point{lat: 32.1, lon: 65.4}];
        let mut ele1 = XMLElement::new("test_element");
        ele1.add_elements_with_name("new_name", ele_vec);
        
        let mut point_ele1: XMLElement = Point{lat: 12.3, lon: 45.6}.into();
        point_ele1.set_name("new_name");
        let mut point_ele2: XMLElement = Point{lat: 32.1, lon: 65.4}.into();
        point_ele2.set_name("new_name");
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: Some(vec![point_ele1, point_ele2]),
            text: None,
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_text() {
        let ele1 = XMLElement::new("test_element").text("some content");
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("some content")),
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_set_text() {
        let mut ele1 = XMLElement::new("test_element");
        ele1.set_text("some content");
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("some content")),
            attrs: None,
            raw: None,
        };
        assert_eq!(ele1, ele2);
    }

    #[test]
    fn xmlelement_to_string() {
        let expected = r#"<test_element a1="42" a2="24"><point lat="12.3" lon="45.6"/><point lat="32.1" lon="65.4"/>some content</test_element>"#;
        

        let point_ele1: XMLElement = Point{lat: 12.3, lon: 45.6}.into();
        let point_ele2: XMLElement = Point{lat: 32.1, lon: 65.4}.into();
        let test_attr1 = XMLAttr{name: String::from("a1"), value: 42.to_string()};
        let test_attr2 = XMLAttr{name: String::from("a2"), value: 24.to_string()};
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: Some(vec![point_ele1, point_ele2]),
            text: Some(String::from("some content")),
            attrs: Some(vec![test_attr1, test_attr2]),
            raw: None,
        };

        assert_eq!(expected, ele2.to_string());
    }

    #[test]
    fn xmlelement_to_string_cdata1() {
        let expected = r#"<test_element><![CDATA[1<2]]></test_element>"#;
        
        let ele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("<![CDATA[1<2]]>")),
            attrs: None,
            raw: None,
        };

        assert_eq!(expected, ele.to_string());
    }

    #[test]
    fn xmlelement_to_string_cdata2() {
        let expected = r#"<test_element>1&lt;2<![CDATA[1<2]]>1&lt;2</test_element>"#;
        
        let ele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("1<2<![CDATA[1<2]]>1<2")),
            attrs: None,
            raw: None,
        };

        assert_eq!(expected, ele.to_string());
    }

    #[test]
    fn xmlelement_to_string_entity_ref_lt() {
        let expected = r#"<test_element>1&lt;2</test_element>"#;
        
        let ele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("1<2")),
            attrs: None,
            raw: None,
        };

        assert_eq!(expected, ele.to_string());
    }

    #[test]
    fn xmlelement_to_string_entity_ref_gt() {
        let expected = r#"<test_element>3&gt;2</test_element>"#;
        
        let ele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("3>2")),
            attrs: None,
            raw: None,
        };

        assert_eq!(expected, ele.to_string());
    }
    #[test]
    fn xmlelement_to_string_entity_ref_amp() {
        let expected = r#"<test_element>5&amp;1=1</test_element>"#;
        
        let ele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("5&1=1")),
            attrs: None,
            raw: None,
        };

        assert_eq!(expected, ele.to_string());
    }
    #[test]
    fn xmlelement_to_string_entity_ref_apos() {
        let expected = r#"<test_element>&apos;a</test_element>"#;
        
        let ele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("'a")),
            attrs: None,
            raw: None,
        };

        assert_eq!(expected, ele.to_string());
    }
    #[test]
    fn xmlelement_to_string_entity_ref_quot() {
        let expected = r#"<test_element>&quot;Hello World&quot;</test_element>"#;
        
        let ele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from(r#""Hello World""#)),
            attrs: None,
            raw: None,
        };

        assert_eq!(expected, ele.to_string());
    }

    #[test]
    fn xmlelement_to_string_pretty1() {
        let expected = format!(r#"<test_element a1="42" a2="24">{}<point lat="12.3" lon="45.6"/>{}<point lat="32.1" lon="65.4"/>{}some content{}</test_element>"#, "\n\t", "\n\t", "\n\t", "\n");

        let point_ele1: XMLElement = Point{lat: 12.3, lon: 45.6}.into();
        let point_ele2: XMLElement = Point{lat: 32.1, lon: 65.4}.into();
        let test_attr1 = XMLAttr{name: String::from("a1"), value: 42.to_string()};
        let test_attr2 = XMLAttr{name: String::from("a2"), value: 24.to_string()};
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: Some(vec![point_ele1, point_ele2]),
            text: Some(String::from("some content")),
            attrs: Some(vec![test_attr1, test_attr2]),
            raw: None,
        };

        assert_eq!(expected, ele2.to_string_pretty("\n","\t"));
    }

    #[test]
    fn xmlelement_to_string_pretty2() {
        let expected = format!(r#"<test_element a1="42" a2="24">{}<point lat="12.3" lon="45.6">{}point content{}</point>{}<point lat="32.1" lon="65.4"/>{}some content{}</test_element>"#, "\n\t", "\n\t\t","\n\t","\n\t", "\n\t", "\n");

        let mut point_ele1: XMLElement = Point{lat: 12.3, lon: 45.6}.into();
        point_ele1.set_text("point content");
        let point_ele2: XMLElement = Point{lat: 32.1, lon: 65.4}.into();
        let test_attr1 = XMLAttr{name: String::from("a1"), value: 42.to_string()};
        let test_attr2 = XMLAttr{name: String::from("a2"), value: 24.to_string()};
        let ele2 = XMLElement{
            name: String::from("test_element"),
            contents: Some(vec![point_ele1, point_ele2]),
            text: Some(String::from("some content")),
            attrs: Some(vec![test_attr1, test_attr2]),
            raw: None,
        };
        assert_eq!(expected, ele2.to_string_pretty("\n","\t"));
    }

    #[test]
    fn xmlelement_to_string_pretty_prolog() {
        let expected = format!(r#"<?xml version="1.0" encoding="UTF-8"?>{}<test_element>{}some content{}</test_element>"#, "\n", "\n\t", "\n");

        let ele = XMLElement{
            name: String::from("test_element"),
            contents: None,
            text: Some(String::from("some content")),
            attrs: None,
            raw: None,
        };

        assert_eq!(expected, ele.to_string_pretty_prolog("\n","\t"));
    }

    #[test]
    fn test_split_cdata() {
        let input = "<![CDATA[]]>";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[]]>"), String::from(""))));

        let input = "<![CDATA[]>";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "<![CDATA[]>");
        assert_eq!(opt_cdata, None);

        let input = "<![CDTA[]]>";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "<![CDTA[]]>");
        assert_eq!(opt_cdata, None);

        let input = "hello<![CDATA[]]>";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "hello");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[]]>"), String::from(""))));

        let input = "hello<![CDATA[]]>world";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "hello");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[]]>"), String::from("world"))));

        let input = "hello<![CDATA[world]]>";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "hello");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[world]]>"), String::from(""))));

        let input = "hello<![CDATA[wor]]>ld";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "hello");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[wor]]>"), String::from("ld"))));

        let input = "<![CDATA[]]>world";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[]]>"), String::from("world"))));

        let input = "<![CDATA[hello]]>world";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[hello]]>"), String::from("world"))));

        let input = "<![CDATA[hel]]>lo]]>world";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[hel]]>"), String::from("lo]]>world"))));

        let input = "<![CDATA[hel<![CDATA[lo]]>world";
        let (before_cdata, opt_cdata) = split_cdata(&input);
        assert_eq!(before_cdata, "");
        assert_eq!(opt_cdata, Some((String::from("<![CDATA[hel<![CDATA[lo]]>"), String::from("world"))));
    }
}