How to indent XML properly using XMLSerializer?

匆匆过客 提交于 2019-12-03 06:18:29

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");

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

I dont know if i was putting it before serializer.startDocument(encoding, standalone) or there was a error with stuff not related to the .xml creation!

Thanks guys!

JonWillis

This is a solution in Java, andriod does support transformer so this should work.

// import additional packages
import java.io.*;

// import DOM related classes
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

// write the output file
try {
  // create a transformer
  TransformerFactory transFactory = TransformerFactory.newInstance();
  Transformer        transformer  = transFactory.newTransformer();

  // set some options on the transformer
  transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

  // get a transformer and supporting classes
  StringWriter writer = new StringWriter();
  StreamResult result = new StreamResult(writer);
  DOMSource    source = new DOMSource(xmlDoc);

  // transform the xml document into a string
  transformer.transform(source, result);

  // open the output file
  FileWriter outputWriter = new FileWriter(outputFile);
  outputWriter.write(writer.toString());
  outputWriter.close();

} catch(javax.xml.transform.TransformerException e) {
  // do something with this error
}catch (java.io.IOException ex) {
  // do something with this error
}
Andrew Taylor

I just wanted to make a note that Transformer.setOutputProperties(Properties) doesn't seems to work for me (1.6.0_26_b03), but Transformer.setOutputProperty(String,String) does perfectly.
If you have a Properties object, you might have to iterate and individually set the output property for it to work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!