aboutsummaryrefslogtreecommitdiffstats
path: root/src/element.rs
blob: b6b3c15dec707dc5f3c2440b6165574dfe3b11aa (plain) (blame)
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
/// elements resemble a final tree, including inherited namespace information
use std::{
    collections::{HashMap, HashSet, VecDeque},
    str::FromStr,
};

use tracing::trace;

use crate::{
    error::{DeserializeError, Error},
    Result,
};

/// Result type for the `FromElement` trait.
pub type DeserializeResult<T> = std::result::Result<T, DeserializeError>;

/// Trait for conversion from an `Element` into another type, for deserialisation from a `Reader`.
pub trait FromElement: Sized {
    fn from_element(element: Element) -> DeserializeResult<Self>;
}

/// Trait for conversion from a type into an `Element`, for serialisation into a `Writer`.
pub trait IntoElement {
    fn builder(&self) -> ElementBuilder;

    fn into_element(&self) -> Element {
        self.builder().build().unwrap()
    }

    fn get_content(&self) -> VecDeque<Content> {
        let element = self.into_element();
        element.content
    }
}

// when are namespaces names chosen then if they are automatically calculated
// namespaces are held by readers and writers.
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct NamespaceDeclaration {
    pub prefix: Option<String>,
    pub namespace: String,
}

// names are qualified, they contain a reference to the namespace (held within the reader/writer)
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct Name {
    pub namespace: Option<String>,
    pub local_name: String,
}

/// `Content` represents anything that can be the content of an XML element.
#[derive(Debug, Clone)]
pub enum Content {
    /// A child element.
    Element(Element),
    /// A text value.
    Text(String),
    /// A processing instruction.
    PI,
    /// A comment.
    Comment(String),
}

// should this be a trait?
/// `Element` represents an XML element that can be written to a `Writer` or read from a `Reader`.
#[derive(Debug, Clone)]
pub struct Element {
    pub(crate) name: Name,
    // namespace: Name,
    // each element once created contains the qualified namespace information for that element
    // the name contains the qualified namespace so this is unnecessary
    // namespace: String,
    // hashmap of explicit namespace declarations on the element itself only
    // possibly not needed as can be calculated at write time depending on context and qualified namespace, and for reading, element validity and namespaces are kept track of by the reader.
    // change this to custom namespace declarations only, so you can override the definition of namespaces if you wish
    pub(crate) namespace_declaration_overrides: HashSet<NamespaceDeclaration>,
    // attributes can be in a different namespace than the element. how to make sure they are valid?
    // maybe include the namespace instead of or with the prefix
    // you can calculate the prefix from the namespaced name and the current writer context
    // you can validate the prefix and calculate the namespace from the current reader context
    // this results in readers and writers being able to return qualification errors as they aren't able to create elements until every part is qualified.
    pub(crate) attributes: HashMap<Name, String>,
    // TODO: make a hashmap maybe? to be able to address parts of the content individually
    pub(crate) content: VecDeque<Content>,
}

impl FromElement for Element {
    fn from_element(element: Element) -> DeserializeResult<Self> {
        Ok(element)
    }
}

impl Element {
    /// Return the namespace the xml element is qualified by, and the localname, for matching on the element when you don't know which kind of element to expect.
    pub fn identify(&self) -> (Option<&str>, &str) {
        (self.name.namespace.as_deref(), &self.name.local_name)
    }

    /// Check the localname of the element.
    pub fn check_name(&self, name: &str) -> DeserializeResult<()> {
        if self.name.local_name == name {
            Ok(())
        } else {
            return Err(DeserializeError::IncorrectName {
                expected: name.to_string(),
                found: self.name.local_name.clone(),
            });
        }
    }

    /// Check the element is qualified by a namespace.
    pub fn check_namespace(&self, namespace: &str) -> DeserializeResult<()> {
        if self.name.namespace.as_deref() == Some(namespace) {
            return Ok(());
        } else {
            if let Some(actual_namespace) = &self.name.namespace {
                return Err(DeserializeError::IncorrectNamespace {
                    expected: namespace.to_string(),
                    found: actual_namespace.clone(),
                });
            } else {
                return Err(DeserializeError::Unqualified {
                    expected: namespace.to_string(),
                });
            }
        }
    }

    /// Optionally extract an attribute from the element.
    pub fn attribute_opt<V: FromStr>(&mut self, att_name: &str) -> DeserializeResult<Option<V>> {
        if let Some(att_value) = self.attributes.remove(&Name {
            namespace: None,
            local_name: att_name.to_string(),
        }) {
            let value = <V as FromStr>::from_str(&att_value)
                .map_err(|_| DeserializeError::FromStr(att_value))?;
            return Ok(Some(value));
        } else {
            return Ok(None);
        }
    }

    /// Optionally extract a namespaced attribute from the elmeent.
    pub fn attribute_opt_namespaced<V: FromStr>(
        &mut self,
        att_name: &str,
        att_namespace: &str,
    ) -> DeserializeResult<Option<V>> {
        if let Some(att_value) = self.attributes.remove(&Name {
            namespace: Some(att_namespace.to_string()),
            local_name: att_name.to_string(),
        }) {
            let value = <V as FromStr>::from_str(&att_value)
                .map_err(|_| DeserializeError::FromStr(att_value))?;
            return Ok(Some(value));
        } else {
            return Ok(None);
        }
    }

    /// Extract an attribute from the element.
    pub fn attribute<V: FromStr>(&mut self, att_name: &str) -> DeserializeResult<V> {
        let name = Name {
            namespace: None,
            local_name: att_name.to_string(),
        };
        if let Some(att_value) = self.attributes.remove(&name) {
            let value = <V as FromStr>::from_str(&att_value)
                .map_err(|_| DeserializeError::FromStr(att_value))?;
            return Ok(value);
        } else {
            return Err(DeserializeError::MissingAttribute(name));
        }
    }

    /// Extract a namespaced attribute from the element.
    pub fn attribute_namespaced<V: FromStr>(
        &mut self,
        att_name: &str,
        att_namespace: &str,
    ) -> DeserializeResult<V> {
        let name = Name {
            namespace: Some(att_namespace.to_string()),
            local_name: att_name.to_string(),
        };
        if let Some(att_value) = self.attributes.remove(&name) {
            let value = <V as FromStr>::from_str(&att_value)
                .map_err(|_| DeserializeError::FromStr(att_value))?;
            return Ok(value);
        } else {
            return Err(DeserializeError::MissingAttribute(name));
        }
    }

    /// Ensure there are no more attributes on the element.
    pub fn no_more_attributes(self) -> DeserializeResult<Self> {
        if self.attributes.is_empty() {
            Ok(self)
        } else {
            Err(DeserializeError::UnexpectedAttributes(self.attributes))
        }
    }

    // for xs:any

    /// Extract a child of type `T` from the element.
    /// E.g. when there is an xs:any.
    pub fn child_one<T: FromElement>(&mut self) -> DeserializeResult<T> {
        if let Some(position) = self.content.iter().position(|content| match content {
            Content::Element(element) => <T as FromElement>::from_element(element.clone()).is_ok(),
            Content::Text(_) => false,
            Content::PI => false,
            Content::Comment(_) => false,
        }) {
            let element = self.content.remove(position).unwrap();
            if let Content::Element(e) = element {
                return <T as FromElement>::from_element(e);
            } else {
                return Err(DeserializeError::MissingChild);
            }
        } else {
            return Err(DeserializeError::MissingChild);
        }
    }

    /// Optionally extract a child of type `T` from the element.
    /// E.g. when there is an xs:any.
    pub fn child_opt<T: FromElement>(&mut self) -> DeserializeResult<Option<T>> {
        if let Some(position) = self.content.iter().position(|content| match content {
            Content::Element(element) => <T as FromElement>::from_element(element.clone()).is_ok(),
            Content::Text(_) => false,
            Content::PI => false,
            Content::Comment(_) => false,
        }) {
            let element = self.content.remove(position).unwrap();
            if let Content::Element(e) = element {
                return Ok(Some(<T as FromElement>::from_element(e)?));
            } else {
                return Err(DeserializeError::MissingChild);
            }
        } else {
            return Ok(None);
        }
    }

    /// Extract several children of type `T` from the element.
    pub fn children<T: FromElement>(&mut self) -> DeserializeResult<Vec<T>> {
        let (children, rest): (VecDeque<_>, VecDeque<_>) = self
            .content
            .clone()
            .into_iter()
            .partition(|content| match content {
                Content::Element(element) => {
                    <T as FromElement>::from_element(element.clone()).is_ok()
                }
                Content::Text(_) => false,
                Content::PI => false,
                Content::Comment(_) => false,
            });
        self.content = rest;
        let children: Vec<T> = children
            .into_iter()
            .map(|content| {
                let child = match content {
                    Content::Element(element) => <T as FromElement>::from_element(element).ok(),
                    Content::Text(_) => None,
                    Content::PI => None,
                    Content::Comment(_) => None,
                }
                .unwrap();
                child
            })
            .collect();
        Ok(children)
    }

    /// Extract a text value from the element.
    pub fn value<V: FromStr>(&mut self) -> DeserializeResult<V> {
        if let Some(position) = self.content.iter().position(|content| match content {
            Content::Element(_) => false,
            Content::Text(s) => <V as FromStr>::from_str(s).is_ok(),
            Content::PI => false,
            Content::Comment(_) => false,
        }) {
            let element = self.content.remove(position).unwrap();
            if let Content::Text(v) = element {
                return Ok(<V as FromStr>::from_str(&v).ok().unwrap());
            } else {
                panic!("infallible")
            }
        } else {
            return Err(DeserializeError::MissingValue);
        }
    }

    /// Optionally extract a text value from the element.
    pub fn value_opt<V: FromStr>(&mut self) -> DeserializeResult<Option<V>> {
        if let Some(position) = self.content.iter().position(|content| match content {
            Content::Element(_) => false,
            Content::Text(s) => <V as FromStr>::from_str(s).is_ok(),
            Content::PI => false,
            Content::Comment(_) => false,
        }) {
            let element = self.content.remove(position).unwrap();
            if let Content::Text(v) = element {
                return Ok(<V as FromStr>::from_str(&v).ok());
            } else {
                panic!("infallible")
            }
        } else {
            return Ok(None);
        }
    }

    // for xs:sequence

    /// Pop a child element of type `T` from the element.
    /// E.g. when there is an xs:sequence.
    pub fn pop_child_one<T: FromElement>(&mut self) -> DeserializeResult<T> {
        loop {
            let child = self
                .content
                .pop_front()
                .ok_or(DeserializeError::MissingChild)?;
            match child {
                Content::Element(element) => return Ok(<T as FromElement>::from_element(element)?),
                Content::Text(_) => {
                    return Err(DeserializeError::UnexpectedContent(self.content.clone()))
                }
                Content::PI => {}
                Content::Comment(_) => {}
            }
        }
    }

    /// Optionally pop a child element of type `T` from the element.
    /// E.g. when there is an xs:sequence.
    pub fn pop_child_opt<T: FromElement>(&mut self) -> DeserializeResult<Option<T>> {
        loop {
            let child = self.content.pop_front();
            if let Some(child) = child {
                match child {
                    Content::Element(element) => {
                        return Ok(Some(<T as FromElement>::from_element(element)?))
                    }
                    Content::Text(_) => {
                        return Err(DeserializeError::UnexpectedContent(self.content.clone()))
                    }
                    Content::PI => {}
                    Content::Comment(_) => {}
                }
            } else {
                return Ok(None);
            }
        }
    }

    /// Pop several children of type `T` from the element.
    /// E.g. when there is an xs:sequence.
    pub fn pop_children<T: FromElement>(&mut self) -> DeserializeResult<Vec<T>> {
        let mut children = Vec::new();
        loop {
            let child = self.content.front();
            trace!("child: {:?}", child);
            if let Some(child) = child {
                match child {
                    Content::Element(element) => {
                        if let Ok(child) = <T as FromElement>::from_element(element.clone()) {
                            trace!("parsed child");
                            children.push(child);
                            self.content.pop_front();
                        } else {
                            trace!("failed to parse child");
                            return Ok(children);
                        }
                    }
                    Content::Text(_) => return Ok(children),
                    Content::PI => {
                        self.content.pop_front();
                        continue;
                    }
                    Content::Comment(_) => {
                        self.content.pop_front();
                        continue;
                    }
                }
            } else {
                return Ok(children);
            }
        }
    }

    /// Pop a text value from the element.
    /// E.g. when there is an xs:sequence.
    pub fn pop_value<V: FromStr>(&mut self) -> DeserializeResult<V> {
        loop {
            let child = self
                .content
                .pop_front()
                .ok_or(DeserializeError::MissingValue)?;
            match child {
                Content::Element(_) => {
                    return Err(DeserializeError::UnexpectedContent(self.content.clone()))
                }
                Content::Text(t) => {
                    return Ok(
                        <V as FromStr>::from_str(&t).map_err(|_| DeserializeError::FromStr(t))?
                    )
                }
                Content::PI => {}
                Content::Comment(_) => {}
            }
        }
    }

    /// Optionally pop a text value from the element.
    /// E.g. when there is an xs:sequence.
    pub fn pop_value_opt<V: FromStr>(&mut self) -> DeserializeResult<Option<V>> {
        loop {
            let child = self.content.pop_front();
            if let Some(child) = child {
                match child {
                    Content::Element(_) => {
                        return Err(DeserializeError::UnexpectedContent(self.content.clone()))
                    }
                    Content::Text(t) => {
                        return Ok(Some(
                            <V as FromStr>::from_str(&t)
                                .map_err(|_| DeserializeError::FromStr(t))?,
                        ))
                    }
                    Content::PI => {}
                    Content::Comment(_) => {}
                }
            } else {
                return Ok(None);
            }
        }
    }

    /// Ensure there is no more element content left.
    pub fn no_more_content(self) -> DeserializeResult<Self> {
        if self
            .content
            .iter()
            .filter(|content| match content {
                Content::Element(_) => true,
                Content::Text(_) => true,
                Content::PI => false,
                Content::Comment(_) => false,
            })
            .collect::<Vec<_>>()
            .is_empty()
        {
            Ok(self)
        } else {
            Err(DeserializeError::UnexpectedContent(self.content))
        }
    }

    /// Create a new `ElementBuilder`.
    pub fn builder(name: impl ToString, namespace: Option<impl ToString>) -> ElementBuilder {
        ElementBuilder::new(name, namespace)
    }
}

/// Builder for the `Element` type.
pub struct ElementBuilder {
    name: Name,
    namespace_declaration_overrides: Vec<NamespaceDeclaration>,
    attributes: Vec<(Name, String)>,
    content: Vec<ContentBuilder>,
}

impl ElementBuilder {
    /// Create a new `ElementBuilder`.
    pub fn new(name: impl ToString, namespace: Option<impl ToString>) -> Self {
        Self {
            name: Name {
                namespace: namespace.map(|namespace| namespace.to_string()),
                local_name: name.to_string(),
            },
            namespace_declaration_overrides: Vec::new(),
            attributes: Vec::new(),
            content: Vec::new(),
        }
    }

    /// Push a namespace declaration override onto the element builder.
    pub fn push_namespace_declaration_override(
        mut self,
        prefix: Option<impl ToString>,
        namespace: impl ToString,
    ) -> Self {
        self.namespace_declaration_overrides
            .push(NamespaceDeclaration {
                prefix: prefix.map(|prefix| prefix.to_string()),
                namespace: namespace.to_string(),
            });
        self
    }

    /// Push an attribute onto the element builder.
    pub fn push_attribute<N: ToString, V: ToString>(mut self, name: N, value: V) -> Self {
        self.attributes.push((
            // TODO: make sure name is a valid name, same for prefixes
            Name {
                namespace: None,
                local_name: name.to_string(),
            },
            value.to_string(),
        ));
        self
    }

    /// Push a namespaced attribute onto the element builder.
    pub fn push_attribute_namespaced(
        mut self,
        namespace: impl ToString,
        name: impl ToString,
        value: impl ToString,
    ) -> Self {
        self.attributes.push((
            Name {
                namespace: Some(namespace.to_string()),
                local_name: name.to_string(),
            },
            value.to_string(),
        ));
        self
    }

    // TODO: use references for everything to avoid cloning
    /// Push a child element onto the element builder.
    pub fn push_child(mut self, child: impl IntoElement) -> Self {
        self.content.push(ContentBuilder::Element(child.builder()));
        self
    }

    // TODO: better way for push_text to work, empty string should be empty element no matter what
    /// Push a text value onto the element builder.
    pub fn push_text(mut self, text: impl ToString) -> Self {
        self.content.push(ContentBuilder::Text(text.to_string()));
        self
    }

    /// Optionally push an attribute onto the element builder.
    pub fn push_attribute_opt(self, name: impl ToString, value: Option<impl ToString>) -> Self {
        if let Some(value) = value {
            self.push_attribute(name, value)
        } else {
            self
        }
    }

    /// Optionally push a namespaced attribute onto the element builder.
    pub fn push_attribute_opt_namespaced(
        self,
        namespace: impl ToString,
        name: impl ToString,
        value: Option<impl ToString>,
    ) -> Self {
        if let Some(value) = value {
            self.push_attribute_namespaced(namespace, name, value)
        } else {
            self
        }
    }

    /// Optionally push a child onto the element builder.
    pub fn push_child_opt(self, child: Option<impl IntoElement>) -> Self {
        if let Some(child) = child {
            self.push_child(child)
        } else {
            self
        }
    }

    /// Optionally push a text value onto the element builder.
    pub fn push_text_opt(self, text: Option<impl ToString>) -> Self {
        if let Some(text) = text {
            self.push_text(text)
        } else {
            self
        }
    }

    /// Optionally push a content item onto the element builder.
    pub fn push_content(mut self, content: ContentBuilder) -> Self {
        self.content.push(content);
        self
    }

    /// Optionally push content items onto the element builder.
    pub fn push_children(self, children: Vec<impl IntoContent>) -> Self {
        let mut element_builder = self;
        for child in children {
            element_builder = element_builder.push_content(child.builder())
        }
        element_builder
    }

    /// Build an `Element` from the `ElementBuilder`.
    pub fn build(&self) -> Result<Element> {
        let mut namespace_declaration_overrides = HashSet::new();
        for namespace_declaration in &self.namespace_declaration_overrides {
            if !namespace_declaration_overrides.insert(namespace_declaration.clone()) {
                return Err(Error::DuplicateNameSpaceDeclaration(
                    namespace_declaration.clone(),
                ));
            }
        }

        let mut attributes = HashMap::new();
        for (att_name, att_value) in &self.attributes {
            if attributes
                .insert(att_name.clone(), att_value.to_string())
                .is_some()
            {
                // TODO: better error
                return Err(Error::DuplicateAttribute(att_name.local_name.to_string()));
            }
        }

        let content: Result<VecDeque<Content>> = self
            .content
            .iter()
            .map(|content_builder| -> Result<Content> { Ok(content_builder.build()?) })
            .collect();
        let content = content?;

        Ok(Element {
            name: self.name.clone(),
            namespace_declaration_overrides,
            attributes,
            content,
        })
    }
}

/// Trait for conversion from a type into an (`Element`) `Content` item.
pub trait IntoContent {
    fn into_content(&self) -> Content {
        self.builder().build().unwrap()
    }

    fn builder(&self) -> ContentBuilder;
}

impl<T> IntoContent for T
where
    T: IntoElement,
{
    fn builder(&self) -> ContentBuilder {
        ContentBuilder::Element(self.builder())
    }
}

/// Trait for conversion from some `Element` `Content` into another type.
pub trait FromContent: Sized {
    fn from_content(content: Content) -> DeserializeResult<Self>;
}

/// Builder for `Content`.
pub enum ContentBuilder {
    /// A child element.
    Element(ElementBuilder),
    /// A text value.
    Text(String),
    /// A comment.
    Comment(String),
}

impl ContentBuilder {
    /// Build a `Content` item from the builder.
    pub fn build(&self) -> Result<Content> {
        match self {
            ContentBuilder::Element(element_builder) => {
                Ok(Content::Element(element_builder.build()?))
            }
            ContentBuilder::Text(text) => Ok(Content::Text(text.to_string())),
            ContentBuilder::Comment(s) => Ok(Content::Comment(s.to_string())),
        }
    }
}

/// Escape a str into an XML escaped string.
pub fn escape_str(s: &str) -> String {
    let mut string = String::new();
    for str in s.split_inclusive(|c| c == '<' || c == '&' || c == '>') {
        if let Some(str) = str.strip_suffix('<') {
            if !str.is_empty() {
                string.push_str(str)
            }
            string.push_str("&lt;");
        } else if let Some(str) = str.strip_suffix('&') {
            if !str.is_empty() {
                string.push_str(str)
            }
            string.push_str("&amp;");
        } else if let Some(str) = str.strip_suffix('>') {
            if !str.is_empty() {
                string.push_str(str)
            }
            string.push_str("&gt;");
        } else {
            if !str.is_empty() {
                string.push_str(str)
            }
        }
    }
    string
}

// impl<'s> TryFrom<xml::Element<'s>> for Element<'s> {
//     type Error = Error;

//     fn try_from(xml_element: xml::Element) -> Result<Self, Self::Error> {
//         match &xml_element {
//             xml::Element::Empty(empty_elem_tag) => {
//                 let namespace_decl;
//                 let attributes;
//                 empty_elem_tag
//                     .attributes
//                     .into_iter()
//                     .filter(|attribute| matches!(attribute, Attribute::NamespaceDeclaration(_)));
//                 todo!()
//             }
//             xml::Element::NotEmpty(stag, content, etag) => todo!(),
//         }
//     }
// }

// example of deriving an element:

// #[derive(XMLWrite, XMLRead)]
// #[peanuts(xmlns = "jabber:client", xmlns:stream = "http://etherx.jabber.org/streams", prefix = "stream")]
// pub struct Stream {
//     from: JID,
//     id: String,
//     to: JID,
//     version: String,
//     #[peanuts(namespace = "http://www.w3.org/XML/1998/namespace")]
//     lang: Lang,
// }

// note: if an element name has a prefix all unprefixed attributes are qualified by the namespace of the prefix, so in this example from's Name's namespace would be "http://etherx.jabber.org/streams"