use std::borrow::Cow;
use name::Name;
use attribute::Attribute;
use common::XmlVersion;
use namespace::{Namespace, NS_NO_PREFIX};
#[derive(Debug)]
pub enum XmlEvent<'a> {
StartDocument {
version: XmlVersion,
encoding: Option<&'a str>,
standalone: Option<bool>
},
ProcessingInstruction {
name: &'a str,
data: Option<&'a str>
},
StartElement {
name: Name<'a>,
attributes: Cow<'a, [Attribute<'a>]>,
namespace: Cow<'a, Namespace>,
},
EndElement {
name: Option<Name<'a>>
},
CData(&'a str),
Comment(&'a str),
Characters(&'a str)
}
impl<'a> XmlEvent<'a> {
#[inline]
pub fn processing_instruction(name: &'a str, data: Option<&'a str>) -> XmlEvent<'a> {
XmlEvent::ProcessingInstruction { name: name, data: data }
}
#[inline]
pub fn start_element<S>(name: S) -> StartElementBuilder<'a> where S: Into<Name<'a>> {
StartElementBuilder {
name: name.into(),
attributes: Vec::new(),
namespace: Namespace::empty().into()
}
}
#[inline]
pub fn end_element() -> EndElementBuilder<'a> {
EndElementBuilder { name: None }
}
#[inline]
pub fn cdata(data: &'a str) -> XmlEvent<'a> { XmlEvent::CData(data) }
#[inline]
pub fn characters(data: &'a str) -> XmlEvent<'a> { XmlEvent::Characters(data) }
#[inline]
pub fn comment(data: &'a str) -> XmlEvent<'a> { XmlEvent::Comment(data) }
}
impl<'a> From<&'a str> for XmlEvent<'a> {
#[inline]
fn from(s: &'a str) -> XmlEvent<'a> { XmlEvent::Characters(s) }
}
pub struct EndElementBuilder<'a> {
name: Option<Name<'a>>
}
impl<'a> EndElementBuilder<'a> {
#[inline]
pub fn name<N>(mut self, name: N) -> EndElementBuilder<'a> where N: Into<Name<'a>> {
self.name = Some(name.into());
self
}
}
impl<'a> From<EndElementBuilder<'a>> for XmlEvent<'a> {
fn from(b: EndElementBuilder<'a>) -> XmlEvent<'a> {
XmlEvent::EndElement { name: b.name }
}
}
pub struct StartElementBuilder<'a> {
name: Name<'a>,
attributes: Vec<Attribute<'a>>,
namespace: Namespace
}
impl<'a> StartElementBuilder<'a> {
#[inline]
pub fn attr<N>(mut self, name: N, value: &'a str) -> StartElementBuilder<'a>
where N: Into<Name<'a>>
{
self.attributes.push(Attribute::new(name.into(), value));
self
}
#[inline]
pub fn ns<S1, S2>(mut self, prefix: S1, uri: S2) -> StartElementBuilder<'a>
where S1: Into<String>, S2: Into<String>
{
self.namespace.put(prefix, uri);
self
}
#[inline]
pub fn default_ns<S>(mut self, uri: S) -> StartElementBuilder<'a>
where S: Into<String>
{
self.namespace.put(NS_NO_PREFIX, uri);
self
}
}
impl<'a> From<StartElementBuilder<'a>> for XmlEvent<'a> {
#[inline]
fn from(b: StartElementBuilder<'a>) -> XmlEvent<'a> {
XmlEvent::StartElement {
name: b.name,
attributes: Cow::Owned(b.attributes),
namespace: Cow::Owned(b.namespace)
}
}
}