Per appiattire mi sa che resta di leggere tutto il file e crearne uno nuovo d'appoggio (orribile e scomodo, però si risolve in 4 righe):
codice:
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.Document;
/**
*
* @author Andrea
*/
public class Esercizio37 {
public static void main (String[] args) {
File base_path = new File ("C:/Users/Andrea/Desktop");
File origin = new File(base_path, "xml.xml");
File dest = new File(base_path, "dest.xml");
try {
FileWriter fw = new FileWriter(dest);
BufferedReader br = new BufferedReader(new FileReader(origin));
String line;
while ((line = br.readLine()) != null) {
fw.write(line);
}
fw.flush();
fw.close();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(dest);
TransformerFactory tFactory = TransformerFactory.newInstance();
tFactory.setAttribute("indent-number", new Integer(2));
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(document);
//Stampol'output sul file xml
StreamResult result1 = new StreamResult(dest);
transformer.transform(source, result1);
//Stampo l'output sulla console
StreamResult result2 = new StreamResult(System.out);
transformer.transform(source, result2);
}
catch (Exception e) {
e.printStackTrace();
}
}
}