Search code examples
javaandroidxml-serializationindentation

How to indent XML properly using XMLSerializer?


I'm having a hard time trying to indent XML files using XMLSerializer.

I've tried

serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",
                      true);

I've tried to append \n into FileWriter but the output is the \n's and \t's at the beginning of the file and not in the right place. I've tried setPropery with the proper URI etc.

Part of the code:

XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
parserFactory .setNamespaceAware(true);
XmlSerializer serializer = parserFactory .newSerializer();
File xmlFile = new File(PATH + ".xml");         
FileWriter writer = new FileWriter(xmlFile);            
serializer.setOutput(writer);
//serializer.setProperty(INDENT_URL, INDENT);
serializer.startDocument("UTF-8", null);
//serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",
                        true);
serializer.startTag(null, "bla");
writer.append('\n');

What am I missing?


Solution

  • Have you tried using these two properties "in combination" on Serializer?

    // indentation as 3 spaces
    serializer.setProperty(
       "http://xmlpull.org/v1/doc/properties.html#serializer-indentation", "   ");
    // also set the line separator
    serializer.setProperty(
       "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n");