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
extern crate svgparser;
extern crate stderrlog;
use std::{env, fs, str};
use std::io::Read;
use svgparser::{
svg,
style,
xmlparser,
AttributeId,
AttributeValue,
ElementId,
StreamError,
};
use xmlparser::{
FromSpan,
StrSpan,
TextUnescape,
XmlSpace,
};
fn main() {
stderrlog::new().module(module_path!()).init().unwrap();
// Get a file path from the args.
let args = env::args().collect::<Vec<String>>();
if args.len() != 2 {
println!("Usage: parser img.svg");
return;
}
// Read a file into the buffer.
let mut file = fs::File::open(&args[1]).unwrap();
let mut text = String::new();
file.read_to_string(&mut text).unwrap();
// Parse an SVG.
if let Err(e) = parse(&text) {
println!("{}", e.to_string());
}
}
// Helper macro for pretty-printing.
macro_rules! print_indent {
($msg:expr, $depth:expr) => ({
write_indent($depth);
println!($msg);
});
($fmt:expr, $depth:expr, $($arg:tt)*) => ({
write_indent($depth);
println!($fmt, $($arg)*);
});
}
fn write_indent(depth: usize) {
for _ in 0..(depth * 4) {
print!(" ");
}
}
fn parse(text: &str) -> Result<(), xmlparser::Error> {
// Control XML nodes depth.
let mut depth = 0;
let mut curr_tag_name = None;
// Begin parsing.
// Loop through tokens.
for token in svg::Tokenizer::from_str(text) {
match token? {
svg::Token::ElementStart(tag_name) => {
print_indent!("Element start: {:?}", depth, tag_name);
curr_tag_name = Some(tag_name.local);
}
svg::Token::Attribute(name, value) => {
match name.local {
svg::Name::Xml(name) => {
print_indent!("Non-SVG attribute: {} = '{}'",
depth + 1, name, value);
}
svg::Name::Svg(aid) => {
if let Some(svg::Name::Svg(eid)) = curr_tag_name {
parse_svg_attribute(eid, name.prefix, aid, value, depth + 1).unwrap();
}
}
}
}
svg::Token::ElementEnd(end) => {
match end {
svg::ElementEnd::Open => {
depth += 1;
}
svg::ElementEnd::Close(_) => {
depth -= 1;
}
svg::ElementEnd::Empty => {}
}
print_indent!("Element end: {:?}", depth, end);
}
svg::Token::Text(text) => {
// 'text' contain text node content as is.
// Basically everything between > and <.
//
// Token::Whitespace will not be emitted inside Token::Text.
//
// Use 'TextUnescape' to convert text entity references,
// remove unneeded spaces and other.
print_indent!("Text node: '{}'", depth,
TextUnescape::unescape(text.to_str(), XmlSpace::Default));
}
svg::Token::Cdata(cdata) => {
// CDATA usually used inside the 'style' element and contain CSS,
// but svgparser doesn't include CSS parser, so you have to use anyone you like.
print_indent!("CDATA node: '{}'", depth + 1, cdata.to_str());
}
svg::Token::Whitespaces(_) => {
// We usually don't care about whitespaces.
}
svg::Token::Comment(comment) => {
println!("Comment node: '{}'", comment);
}
svg::Token::EntityDeclaration(name, value) => {
// svgparser supports only 'ENTITY'.
// Any other DTD node will be ignored.
println!("Entity declaration: '{}' = '{}'", name, value.to_str());
}
svg::Token::Declaration(version, encoding, standalone) => {
println!("Declaration node: version={} encoding={:?} standalone={:?}",
version, encoding, standalone);
}
svg::Token::ProcessingInstruction(target, content) => {
println!("Processing Instruction node: target={}, content={:?}",
target, content);
}
}
}
Ok(())
}
fn parse_svg_attribute(
eid: ElementId,
prefix: &str,
aid: AttributeId,
value: StrSpan,
depth: usize,
) -> Result<(), StreamError> {
// SVG attributes parsing should be done 'manually'.
// svgparser doesn't parse attributes by default because it can be
// very expensive (in a case of paths).
// So you can decide for yourself what to do with attributes.
// We need ElementId for attribute parsing.
// See 'from_span' documentation for details.
let av = AttributeValue::from_span(eid, prefix, aid, value)?;
match av {
AttributeValue::Path(tokenizer) => {
print_indent!("Path:", depth);
// By the SVG spec, any invalid data occurred in the path should
// stop parsing of this path, but not the whole document.
for segment in tokenizer {
print_indent!("{:?}", depth + 1, segment)
}
}
AttributeValue::Points(tokenizer) => {
print_indent!("Points:", depth);
// By the SVG spec, any invalid data occurred in the `points` should
// stop parsing of this attribute, but not the whole document.
for point in tokenizer {
print_indent!("{:?}", depth + 1, point)
}
}
AttributeValue::Style(tokenizer) => {
print_indent!("Style:", depth);
for token in tokenizer {
match token? {
style::Token::XmlAttribute(name, value) => {
print_indent!("Non-SVG attribute: {} = '{}'", depth + 1, name, value);
}
style::Token::SvgAttribute(aid, value) => {
parse_svg_attribute(eid, "", aid, value, depth + 1)?;
}
style::Token::EntityRef(name) => {
print_indent!("Entity reference: {}", depth + 1, name)
}
}
}
}
AttributeValue::Transform(tokenizer) => {
print_indent!("Transform:", depth);
for ts in tokenizer {
print_indent!("{:?}", depth + 1, ts?)
}
}
_ => {
print_indent!("SVG attribute: {:?} = {:?}", depth, aid, av);
}
}
// Note that 'class' attribute should be parsed manually if needed.
Ok(())
}