Skip to main content

viral32111_xml/
declaration.rs

1use super::attributes;
2use std::error::Error;
3
4/// Represents an XML declaration.
5pub struct Declaration {
6	pub version: String,
7	pub encoding: String,
8	pub standalone: String,
9}
10
11/// Parses the attributes within an XML declaration.
12pub fn parse(text: &str) -> Result<(Declaration, usize), Box<dyn Error>> {
13	// Don't bother if we do not begin properly
14	if !text.starts_with("<?xml") {
15		return Err("XML declaration missing".into());
16	}
17
18	// Find the end
19	let declaration_end_position = text.find("?>").expect("XML declaration not terminated") + 2;
20	let declaration = &text[..declaration_end_position];
21
22	// Parse the XML declaration
23	let attributes = attributes::parse(&declaration[5..declaration.len() - 2]);
24	let version = attributes
25		.get("version")
26		.expect("XML declaration missing version attribute");
27	let encoding = attributes
28		.get("encoding")
29		.expect("XML declaration missing encoding attribute");
30	let standalone = attributes
31		.get("standalone")
32		.expect("XML declaration missing standalone attribute");
33
34	// Return the attributes & where it ends
35	Ok((
36		Declaration {
37			version,
38			encoding,
39			standalone,
40		},
41		declaration_end_position,
42	))
43}