xml/writer/events.rs
1//! Contains `XmlEvent` datatype, instances of which are consumed by the writer.
2
3use std::borrow::Cow;
4
5use name::Name;
6use attribute::Attribute;
7use common::XmlVersion;
8use namespace::{Namespace, NS_NO_PREFIX};
9
10/// A part of an XML output stream.
11///
12/// Objects of this enum are consumed by `EventWriter`. They correspond to different parts of
13/// an XML document.
14#[derive(Debug)]
15pub enum XmlEvent<'a> {
16 /// Corresponds to XML document declaration.
17 ///
18 /// This event should always be written before any other event. If it is not written
19 /// at all, a default XML declaration will be outputted if the corresponding option
20 /// is set in the configuration. Otherwise an error will be returned.
21 StartDocument {
22 /// XML version.
23 ///
24 /// Defaults to `XmlVersion::Version10`.
25 version: XmlVersion,
26
27 /// XML document encoding.
28 ///
29 /// Defaults to `Some("UTF-8")`.
30 encoding: Option<&'a str>,
31
32 /// XML standalone declaration.
33 ///
34 /// Defaults to `None`.
35 standalone: Option<bool>
36 },
37
38 /// Denotes an XML processing instruction.
39 ProcessingInstruction {
40 /// Processing instruction target.
41 name: &'a str,
42
43 /// Processing instruction content.
44 data: Option<&'a str>
45 },
46
47 /// Denotes a beginning of an XML element.
48 StartElement {
49 /// Qualified name of the element.
50 name: Name<'a>,
51
52 /// A list of attributes associated with the element.
53 ///
54 /// Currently attributes are not checked for duplicates (TODO). Attribute values
55 /// will be escaped, and all characters invalid for attribute values like `"` or `<`
56 /// will be changed into character entities.
57 attributes: Cow<'a, [Attribute<'a>]>,
58
59 /// Contents of the namespace mapping at this point of the document.
60 ///
61 /// This mapping will be inspected for "new" entries, and if at this point of the document
62 /// a particular pair of prefix and namespace URI is already defined, no namespace
63 /// attributes will be emitted.
64 namespace: Cow<'a, Namespace>,
65 },
66
67 /// Denotes an end of an XML element.
68 EndElement {
69 /// Optional qualified name of the element.
70 ///
71 /// If `None`, then it is assumed that the element name should be the last valid one.
72 /// If `Some` and element names tracking is enabled, then the writer will check it for
73 /// correctness.
74 name: Option<Name<'a>>
75 },
76
77 /// Denotes CDATA content.
78 ///
79 /// This event contains unparsed data, and no escaping will be performed when writing it
80 /// to the output stream.
81 CData(&'a str),
82
83 /// Denotes a comment.
84 ///
85 /// The string will be checked for invalid sequences and error will be returned by the
86 /// write operation
87 Comment(&'a str),
88
89 /// Denotes character data outside of tags.
90 ///
91 /// Contents of this event will be escaped if `perform_escaping` option is enabled,
92 /// that is, every character invalid for PCDATA will appear as a character entity.
93 Characters(&'a str)
94}
95
96impl<'a> XmlEvent<'a> {
97 /// Returns an writer event for a processing instruction.
98 #[inline]
99 pub fn processing_instruction(name: &'a str, data: Option<&'a str>) -> XmlEvent<'a> {
100 XmlEvent::ProcessingInstruction { name: name, data: data }
101 }
102
103 /// Returns a builder for a starting element.
104 ///
105 /// This builder can then be used to tweak attributes and namespace starting at
106 /// this element.
107 #[inline]
108 pub fn start_element<S>(name: S) -> StartElementBuilder<'a> where S: Into<Name<'a>> {
109 StartElementBuilder {
110 name: name.into(),
111 attributes: Vec::new(),
112 namespace: Namespace::empty().into()
113 }
114 }
115
116 /// Returns a builder for an closing element.
117 ///
118 /// This method, unline `start_element()`, does not accept a name because by default
119 /// the writer is able to determine it automatically. However, when this functionality
120 /// is disabled, it is possible to specify the name with `name()` method on the builder.
121 #[inline]
122 pub fn end_element() -> EndElementBuilder<'a> {
123 EndElementBuilder { name: None }
124 }
125
126 /// Returns a CDATA event.
127 ///
128 /// Naturally, the provided string won't be escaped, except for closing CDATA token `]]>`
129 /// (depending on the configuration).
130 #[inline]
131 pub fn cdata(data: &'a str) -> XmlEvent<'a> { XmlEvent::CData(data) }
132
133 /// Returns a regular characters (PCDATA) event.
134 ///
135 /// All offending symbols, in particular, `&` and `<`, will be escaped by the writer.
136 #[inline]
137 pub fn characters(data: &'a str) -> XmlEvent<'a> { XmlEvent::Characters(data) }
138
139 /// Returns a comment event.
140 #[inline]
141 pub fn comment(data: &'a str) -> XmlEvent<'a> { XmlEvent::Comment(data) }
142}
143
144impl<'a> From<&'a str> for XmlEvent<'a> {
145 #[inline]
146 fn from(s: &'a str) -> XmlEvent<'a> { XmlEvent::Characters(s) }
147}
148
149pub struct EndElementBuilder<'a> {
150 name: Option<Name<'a>>
151}
152
153/// A builder for a closing element event.
154impl<'a> EndElementBuilder<'a> {
155 /// Sets the name of this closing element.
156 ///
157 /// Usually the writer is able to determine closing element names automatically. If
158 /// this functionality is enabled (by default it is), then this name is checked for correctness.
159 /// It is possible, however, to disable such behavior; then the user must ensure that
160 /// closing element name is correct manually.
161 #[inline]
162 pub fn name<N>(mut self, name: N) -> EndElementBuilder<'a> where N: Into<Name<'a>> {
163 self.name = Some(name.into());
164 self
165 }
166}
167
168impl<'a> From<EndElementBuilder<'a>> for XmlEvent<'a> {
169 fn from(b: EndElementBuilder<'a>) -> XmlEvent<'a> {
170 XmlEvent::EndElement { name: b.name }
171 }
172}
173
174/// A builder for a starting element event.
175pub struct StartElementBuilder<'a> {
176 name: Name<'a>,
177 attributes: Vec<Attribute<'a>>,
178 namespace: Namespace
179}
180
181impl<'a> StartElementBuilder<'a> {
182 /// Sets an attribute value of this element to the given string.
183 ///
184 /// This method can be used to add attributes to the starting element. Name is a qualified
185 /// name; its namespace is ignored, but its prefix is checked for correctness, that is,
186 /// it is checked that the prefix is bound to some namespace in the current context.
187 ///
188 /// Currently attributes are not checked for duplicates. Note that duplicate attributes
189 /// are a violation of XML document well-formedness.
190 ///
191 /// The writer checks that you don't specify reserved prefix names, for example `xmlns`.
192 #[inline]
193 pub fn attr<N>(mut self, name: N, value: &'a str) -> StartElementBuilder<'a>
194 where N: Into<Name<'a>>
195 {
196 self.attributes.push(Attribute::new(name.into(), value));
197 self
198 }
199
200 /// Adds a namespace to the current namespace context.
201 ///
202 /// If no namespace URI was bound to the provided prefix at this point of the document,
203 /// then the mapping from the prefix to the provided namespace URI will be written as
204 /// a part of this element attribute set.
205 ///
206 /// If the same namespace URI was bound to the provided prefix at this point of the document,
207 /// then no namespace attributes will be emitted.
208 ///
209 /// If some other namespace URI was bound to the provided prefix at this point of the document,
210 /// then another binding will be added as a part of this element attribute set, shadowing
211 /// the outer binding.
212 #[inline]
213 pub fn ns<S1, S2>(mut self, prefix: S1, uri: S2) -> StartElementBuilder<'a>
214 where S1: Into<String>, S2: Into<String>
215 {
216 self.namespace.put(prefix, uri);
217 self
218 }
219
220 /// Adds a default namespace mapping to the current namespace context.
221 ///
222 /// Same rules as for `ns()` are also valid for the default namespace mapping.
223 #[inline]
224 pub fn default_ns<S>(mut self, uri: S) -> StartElementBuilder<'a>
225 where S: Into<String>
226 {
227 self.namespace.put(NS_NO_PREFIX, uri);
228 self
229 }
230}
231
232impl<'a> From<StartElementBuilder<'a>> for XmlEvent<'a> {
233 #[inline]
234 fn from(b: StartElementBuilder<'a>) -> XmlEvent<'a> {
235 XmlEvent::StartElement {
236 name: b.name,
237 attributes: Cow::Owned(b.attributes),
238 namespace: Cow::Owned(b.namespace)
239 }
240 }
241}