8

Noticed that some existing code that reads and writes a simple XML file (defined by a DTD) is using deprecated classes. Want to replace the following with non-deprecated classes. Since using Java 6, hoping to use the packages included for XML processing rather than 3rd party tool (though standard things like jdom would be possible).

OutputFormat format = new OutputFormat( doc );
format.setLineWidth( 100 );
format.setIndenting( true );
format.setIndent( 2 );

Here's an attempt using TransformerFactory which is mentioned in various SO answers. Specifying the indentation above doesn't seem too hard, though not as obvious as expected. But how to specify a line length?

TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", Integer.valueOf(4));
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result =  new StreamResult(writer);
transformer.transform(source, result);

Also noticing that the file is created with DOS formatting whereas the above is unix format. Is there a better approach than this? This is a pretty simple file that doesn't need much formatting, just want it to be readable by a person in addition to a program.

Cincinnati Joe
  • 2,077
  • 6
  • 23
  • 32
  • Well, now I'm not sure if the indent number is even working. I've tried the above as well as transformer.setOutputProperty and am getting inconsistent results. (Also now getting increasing whitespace in parts of output file if I roundtrip read then write). Looks like com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl is getting instantiated by the code above, if that matters. – Cincinnati Joe Jul 19 '11 at 20:25
  • AFAIK the DOS vs Unix linefeeds depend on where you run your code (DOS/Windows vs Unix) if you use the builtin serializer. If you want absolute control create your own stylesheet for pretty-printing. – Queeg Jul 22 '21 at 21:51

0 Answers0