0

A More Convenient Way to Write Out Start and End XML Tags in Java using Lambda

Did you miss writing out an XML element end tag in your Java codes? It is fine when generating small XML documents because spotting the erring codes is relatively easy. However, things may get very frustrating when we are writing huge XML documents with numerous elements that may be recursive or hierarchical in structure  even if you validate it against some XSDs.

So, how about using JAXB? Not an option! It is too slow. Most people who have dealt with XMLs avoid it.

Using XMLStreamWriter

Now consider the following Java codes.

What if you missed out the code in either line 15 or 16?

Using Lambda

We need some sort of a wrapper class from which to use the @FunctionalInterface

First, this is our functional interface:

The wrapper class looks something like this:

For simplicity, an XMLStreamWriter object is passed to the constructor.

Modified XmlWriterDemo.java

The codes above are made as simple as possible to demonstrate the idea of using Lambda for writing out XML tags. It is even possible to create a method  writeStartDocumentBlock(String, RecursiveElementWriterFunctionalInterface)  for writeStartDocument and writeEndDocument  methods.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert