Search code examples
javawhitespacesimple-framework

Simple Framework: Eliminating unwanted white space in serialized XML


Question:

How to eliminate unnecessary white space characters from the serialized XML while using Simple framework?

Details:

Let's consider this very basic example from the Simple framework website. The XML output is:

<example index="123">
   <text>Example message</text>
</example>

How do I instruct the serializer to output this instead?

<example index="123"><text>Example message</text></example>

I checked the org.simpleframework.xml.stream.Style interface, but it only seems to be able to work on individual element and attribute names and not the content.


Solution

  • You can use Format class for this:

    Usage:

    final Format format = new Format(0);
    
    Serializer ser = new Persister(format);
    ser.write(new Example(123, "Example message"), new File("out.xml"));
    

    Assuming that your Example class looks something like this:

    @Root
    public class Example
    {
        @Attribute(name="index", required=true)
        private int index;
        @Element(name="text", required=true)
        private String text;
    
    
        public Example(int index, String text)
        {
            this.index = index;
            this.text = text;
        }
    
    
        // ...
    
    }
    

    You'll get the following XML (File out.xml) with the Serializer code from above:

    <example index="123"><text>Example message</text></example>