From 93174f97eca068758c6678888cffa7ecc3d28098 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20=E2=80=9Cpep=E2=80=9D=20Buquet?= Date: Mon, 9 Jan 2023 13:26:30 +0100 Subject: [PATCH] minidom: Allow passing prefixes alongside a reader MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Maxime “pep” Buquet --- minidom/src/element.rs | 31 +++++++++++++++++++++++++++++++ minidom/src/tree_builder.rs | 9 +++++++++ 2 files changed, 40 insertions(+) diff --git a/minidom/src/element.rs b/minidom/src/element.rs index 674b0ecf..6f4d8a16 100644 --- a/minidom/src/element.rs +++ b/minidom/src/element.rs @@ -346,6 +346,25 @@ impl Element { Err(Error::EndOfDocument) } + /// Parse a document from a `BufRead`, allowing Prefixes to be specified. Useful to provide + /// knowledge of namespaces that would have been declared on parent elements not present in the + /// reader. + pub fn from_reader_with_prefixes>( + reader: R, + prefixes: P, + ) -> Result { + let mut tree_builder = TreeBuilder::new().with_prefixes_stack(vec![prefixes.into()]); + let mut driver = PullDriver::wrap(reader, Lexer::new(), RawParser::new()); + while let Some(event) = driver.read()? { + tree_builder.process_event(event)?; + + if let Some(root) = tree_builder.root.take() { + return Ok(root); + } + } + Err(Error::EndOfDocument) + } + /// Output a document to a `Writer`. pub fn write_to(&self, writer: &mut W) -> Result<()> { self.to_writer(&mut ItemWriter::new(writer)) @@ -958,4 +977,16 @@ mod tests { assert_eq!(elem, elem3); assert_eq!(elem, elem4); } + + #[test] + fn test_from_reader_with_prefixes() { + let xml = b""; + let elem = + Element::from_reader_with_prefixes(&xml[..], String::from("jabber:client")).unwrap(); + + let xml2 = b""; + let elem2 = Element::from_reader(&xml2[..]).unwrap(); + + assert_eq!(elem, elem2); + } } diff --git a/minidom/src/tree_builder.rs b/minidom/src/tree_builder.rs index aed524ed..59df32e8 100644 --- a/minidom/src/tree_builder.rs +++ b/minidom/src/tree_builder.rs @@ -29,6 +29,15 @@ impl TreeBuilder { } } + /// Allow setting prefixes stack. + /// + /// Useful to provide knowledge of namespaces that would have been declared on parent elements + /// not present in the reader. + pub fn with_prefixes_stack(mut self, prefixes_stack: Vec) -> Self { + self.prefixes_stack = prefixes_stack; + self + } + /// Stack depth pub fn depth(&self) -> usize { self.stack.len()