2012-12-18 26 views
8

Tôi đã tạo một số mã viết bản đồ cho XML. Dường như nó hoạt động nhưng tệp được in không có dòng mới. Vì vậy, trong bất kỳ trình soạn thảo XML nào chỉ có trên một dòng. Làm thế nào tôi có thể in ra một dòng mới cho mỗi đứa trẻ?Tạo XML chỉ in thành một dòng

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

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

Trả lời

19

tôi sử dụng

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"); 

Mà dường như chỉ làm việc tốt.

+0

Điều này phù hợp với tôi. Cảm ơn – Tony

+0

@Tony Điều này nhỏ với tôi vài tuần cho Googling và dùng thử và lỗi. Rất vui vì tôi đã cứu bạn;) – MadProgrammer

Các vấn đề liên quan