JAXB Marshaller and Formatting of output XML

Viewed 3826

I was following this post:
JAXB Marshaller indentation

But I ran to an error:

org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

Which actually pertains to the Marshaller I have used when it did:

marshaller.marshal(instance, domResult);

Your comments and opinions are highly appreciated.

Cheers,
Artanis Zeratul

1 Answers

I fixed my problem by tweaking Antonio Maria Sanchez's answer a bit.
Reference: JAXB Marshaller indentation


So here is my answer:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class ObjectToXMLWriter {
    public static <Type> boolean writeToFileWithXmlTransformer(Type instance
            ,String fullFileNamePath) throws FileNotFoundException {
        boolean isSaved = false;
        JAXBContext jaxBContent = null;
        Marshaller marshaller = null;
        StringWriter stringWriter = new StringWriter();

        try {
            jaxBContent = JAXBContext.newInstance(instance.getClass());
            marshaller = jaxBContent.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(instance, stringWriter);

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            transformer.transform(new StreamSource(new StringReader(stringWriter.toString()))
                    ,new StreamResult(new File(fullFileNamePath)));

           isSaved = true; 
        } catch(JAXBException jaxBException) {
            System.out.println("JAXBException happened!");
            jaxBException.printStackTrace();
        } catch(Exception exception) {
            System.out.println("Exception happened!");
            exception.printStackTrace();
        }

        return isSaved;
    }
}


The critical points to this answer are the following:

  • marshaller.marshal(instance, stringWriter);
    • instead of using DOMResult
  • transformer.transform(new StreamSource(new StringReader(stringWriter.toString())) ,new StreamResult(new File(fullFileNamePath)));
    • instead of using DOMSource


Cheers,
Artanis Zeratul

Related