Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML formatting in java - Mainting the state indent

I have an XML file that I open and edit few attributes in the node and then save it back, but due to some reason whatsoever the saved XML's are not indented properly as the one before.

Here my code through which I save the XML file:

    TransformerFactory transformerFactory = TransformerFactory.newInstance();       
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(Path));
    transformer.transform(source, result); 

Although I have specified

transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 

the XML is not indented properly, I would like to have the XML in the state as it was before (except the changes that were made)

Any help will be really appreciated.

Thanks a lot in advance.

like image 368
spaniard89 Avatar asked Oct 31 '22 22:10

spaniard89


1 Answers

You need to enable 'INDENT' and set the indent amount for the transformer:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

See if this works.

like image 158
Arash Saidi Avatar answered Nov 12 '22 20:11

Arash Saidi