2012-12-18 12 views
8

Ho creato un codice che scrive una mappa in XML. Sembra funzionare ma il file viene stampato senza nuove righe. Quindi, in qualsiasi editor XML è solo su una riga. Come posso stampare su una nuova riga per ogni bambino?Creazione di XML che stampa solo su una riga

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.newDocument(); 

Element vdata = doc.createElement("vouchdata"); 
doc.appendChild(vdata); 

for (Entry<String, String> entry : vouchMap.entrySet()) { 
    Element udata = doc.createElement("vouch"); 

    Attr vouchee = doc.createAttribute("name"); 
    vouchee.setValue(entry.getKey()); 
    udata.setAttributeNode(vouchee); 

    Attr voucher = doc.createAttribute("vouchedBy"); 
    voucher.setValue(entry.getValue()); 
    udata.setAttributeNode(voucher); 

    vdata.appendChild(udata); 
} 

// write the content into xml file 
TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer(); 
DOMSource source = new DOMSource(doc); 
StreamResult result = new StreamResult(new File("vouchdata.xml")); 

// Output to console for testing 
// StreamResult result = new StreamResult(System.out); 

transformer.transform(source, result); 
+3

Vedi http://stackoverflow.com/questions/1264849/pretty-printing-output-from-javax-xml-transform -transformer-with-only-standard-j –

risposta

19

Io uso

Transformer tf = TransformerFactory.newInstance().newTransformer(); 
tf.setOutputProperty(OutputKeys.INDENT, "yes"); 
tf.setOutputProperty(OutputKeys.METHOD, "xml"); 
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); 

che sembra funzionare bene.

+0

Questo ha funzionato per me. Grazie – Tony

+0

@Tony Questo piccolo trucco per me settimane per Google e prove ed errori. Contento di averti salvato l'hasel;) – MadProgrammer

Problemi correlati