Rust, Software Development

Write XML Tags using Closure in Rust – No Element End Tags

Did you miss writing out an XML element end tag in your Rust codes? Even when you have the best tools, this kind of mistake is not hard to make, and working with XML files is always ugly. We can improve the way we code, though. There is a convenient way to avoid this in Rust using Closure.

Coming From Java

In Java, a similar implementation can be achieved using Lambda. For more information, please see A More Convenient Way to Write Out Start and End XML Tags in Java using Lambda

Requirements

We will use the following.

  • Rust 1.38.0
  • Cargo
  • xml-rs 0.8.0
    • Used for writing XML files
  • Intellij IDEA
  • Rust plugin for Intellij IDEA

Writing Out XML Tags Is Ugly

Do we want to write XMLs using the following codes? Do we always need to specify the closing tags or codes?

For example, line 1 matches line 26. Line 5 ends at line 12 and line 16 for line 23. How can we avoid that kind of coding? We can use Closure and design our codes in such a way we only work with the start elements.

Writing XML using Closure

Writing codes using Closures does not need any crates. However, we need to use crates designed for XML writing, at least. In this post, we will use the xml-rs crate to write out XML, but our closure codes wrap codes from xml-rs.

Update Cargo.toml – Include xml-rs only

We only need one crate for this post. It is enough for our purpose of creating codes that use Rust Closures.

The Application Codes – Main.rs

First, we specify the use of statements that we need.

Then, we create a function that accepts a closure plus other things. If we take a closer look at the codes, we are using codes from xml-rs codes to write out the start and end XML tag elements.

Next, create a function that makes calls to write_element_block  function. The handle_event function writes out the whole XML and uses the write_element_block to write out the major parts of the document. The major components are HEAD, which has the TITLE element, and BODY, which has the DIV element. Cool, no?

We did not even write codes that close off those elements and only specified the start element tag name.

Finally, we have the primary function where we call the handle_event function.

The codes write XML data to a file called output.xml with the following contents.

That is how we can create codes that conveniently write XML tags using Closures in Rust.

This post is now part of Rust Programming Language For Beginners Tutorial.

You Might Also Like