Skip to content

Commit 5ff6881

Browse files
committed
Add ignoring_comments option to TreeBuildHandler.
1 parent 693afae commit 5ff6881

1 file changed

Lines changed: 27 additions & 4 deletions

File tree

src/tree/mod.rs

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,10 @@ pub struct TreeBuildHandler<H: SAXHandler = DefaultSAXHandler> {
143143
///
144144
/// The default value is `false`.
145145
pub coalescing: bool,
146+
/// If true, the `Comment` node is not created.
147+
///
148+
/// The default value is `false`.
149+
pub ignoring_comments: bool,
146150
}
147151

148152
impl<H: SAXHandler> TreeBuildHandler<H> {
@@ -156,6 +160,7 @@ impl<H: SAXHandler> TreeBuildHandler<H> {
156160
in_cdata: false,
157161
expand_entity_reference: true,
158162
coalescing: false,
163+
ignoring_comments: false,
159164
}
160165
}
161166
}
@@ -171,6 +176,7 @@ impl Default for TreeBuildHandler {
171176
in_cdata: false,
172177
expand_entity_reference: true,
173178
coalescing: false,
179+
ignoring_comments: false,
174180
}
175181
}
176182
}
@@ -252,10 +258,12 @@ impl<H: SAXHandler> SAXHandler for TreeBuildHandler<H> {
252258
}
253259

254260
fn comment(&mut self, data: &str) {
255-
self.node
256-
.append_child(self.document.create_comment(data))
257-
.unwrap();
258-
self.handler.comment(data);
261+
if !self.ignoring_comments {
262+
self.node
263+
.append_child(self.document.create_comment(data))
264+
.unwrap();
265+
self.handler.comment(data);
266+
}
259267
}
260268

261269
fn declaration(&mut self, version: &str, encoding: Option<&str>, standalone: Option<bool>) {
@@ -677,4 +685,19 @@ mod tests {
677685
r#"<doc><ch1>abc</ch1><ch2>abcdef</ch2><ch3>abcdef</ch3><ch4>abcdefghi</ch4></doc>"#
678686
)
679687
}
688+
689+
#[test]
690+
fn ignoring_comments_tests() {
691+
const DOCUMENT: &str = r#"<!--comment--><doc><!--comment--><ch1><!--comment--></ch1><!--comment--></doc><!--comment-->"#;
692+
693+
let handler = TreeBuildHandler {
694+
ignoring_comments: true,
695+
..Default::default()
696+
};
697+
let mut reader = XMLReader::builder().set_handler(handler).build();
698+
reader.parse_str(DOCUMENT, None).unwrap();
699+
let document = reader.handler.document;
700+
let ret = document.to_string();
701+
assert_eq!(ret, r#"<doc><ch1 /></doc>"#)
702+
}
680703
}

0 commit comments

Comments
 (0)