Interview Questions

JAXB - Avoid converting < into &lt; and > into &gt; during Marshalling

In this article, let us see how to avoid converting < to &lt ; and > to &gt ; and & to &amp ; during JAXB Marshalling operation.

1. CharacterEscapeHandler creation
Create a custom Escape Handler by implementing the CharacterEscapeHandler interface as given below.

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;

public class JaxbCharacterEscapeHandler implements CharacterEscapeHandler {

        public void escape(char[] buf, int start, int len, boolean isAttValue,
                        Writer out) throws IOException {

                for (int i = start; i < start + len; i++) {
                        char ch = buf[i];

2. Marshaller Code
Use the below code snippet for JAXB Marshalling operation.

Note: Please go through the basics of using JAXB Marshalling code samples before using this example

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
import com.sun.xml.bind.marshaller.DataWriter;

public class JaxbMarshaller {

        public static void main(String[] args) {

                // Note: Provide input for the below objects
                Object jaxbObject = null; // Create the right Input object
                String packageName = jaxbObject.getClass().getPackage().getName(); // Provide the package name of the generated classes
                try {
                        JAXBContext jaxbContext = JAXBContext.newInstance(packageName);
                        Marshaller marshaller = jaxbContext.createMarshaller();

                        // Set UTF-8 Encoding
                        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

                        // The below code will take care of avoiding the conversion of < to &lt; and > to &gt; etc
                        StringWriter stringWriter = new StringWriter();
                        PrintWriter printWriter = new PrintWriter(stringWriter);
                        DataWriter dataWriter = new DataWriter(printWriter, "UTF-8", new JaxbCharacterEscapeHandler());
                        // Perform Marshalling operation
                        marshaller.marshal(jaxbObject, dataWriter);

                } catch (JAXBException e) {
                        System.err.println("Error in marshalling...");