2

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.

curioustechizen
  • 10,572
  • 10
  • 61
  • 110
  • 1
    Just out of curiosity: Why do you want to do this? –  Nov 05 '12 at 08:43
  • 1
    @Tichodroma Efficiency and Bandwidth. I have a large XML as response to my REST API. The tags and content are ... sparse. The newlines take up a noticeable chunk of the response body. I figure that eliminating the unneeded characters will not only lower the data transferred over the wire; it will also improve parsing efficiency on the client side. I cannot use GZip encoding since my API also serves a constrained embedded device which does not have gunzip capability. – curioustechizen Nov 05 '12 at 08:58

1 Answers1

8

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>
ollo
  • 24,797
  • 14
  • 106
  • 155
  • Thanks. That works like a charm. I was always under the assumption that a `0` passed to `indent` argument to the `Format` object would still introduce a new line, but all the elements would be left-aligned! – curioustechizen Nov 06 '12 at 05:50