Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure Unix-style line endings used when generating XML on Windows with Java

I am currently outputting an XML document to a file in Java as follows:

final Document xmldoc = toXMLDocument(docTheory);

// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(xmldoc);
StreamResult result = new StreamResult(file);

transformer.transform(source, result);

However, when run on Windows, this produces output with Windows-style line-endings. I would like to have Unix-style line endings produced regardless of OS. How I can do this?

like image 504
Ryan Gabbard Avatar asked Dec 22 '25 05:12

Ryan Gabbard


2 Answers

The difference between operating systems is because it is used internally the method println . Before saving the file, change the line separator:

System.setProperty("line.separator", "\n");

You could use a static block.

like image 160
Paul Vargas Avatar answered Dec 23 '25 19:12

Paul Vargas


If you use LSSerializer rather than Transformer, you can use LSSerializer.setNewLine to control newlines.

like image 24
ykaganovich Avatar answered Dec 23 '25 17:12

ykaganovich