Reputation: 25
So im trying to get an XML from an arraylist. my program is working as expected except the resulting XML is all in one line, element after element, instead of having the usual XML format. Here is my code:
public static void obtenirClientsXml(ArrayList<Client> llistaClients){
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element eRoot = doc.createElement("llista_clients");
doc.appendChild(eRoot);
// recorremos el array list
Iterator<Client> i = llistaClients.iterator();
while (i.hasNext()){
Client c = i.next();
Element eClient = doc.createElement("client");
eRoot.appendChild(eClient);
Element eNom = doc.createElement("nom");
eNom.appendChild(doc.createTextNode(c.getNom()));
eClient.appendChild(eNom);
Element eCognom = doc.createElement("cognom");
eCognom.appendChild(doc.createTextNode(c.getCognoms()));
eClient.appendChild(eCognom);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult("C:/RentalClot/Clients/clients.xml");
transformer.transform(source, result);
} catch (Exception e){
e.printStackTrace();
}
}
any ideas?
Upvotes: 1
Views: 425
Reputation: 25
find the solution just changed to:
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(doc);
StreamResult result = new StreamResult("C:/RentalClot/Clients/clients.xml");
transformer.transform(source, result);
now works as suposed.
Upvotes: 0
Reputation: 155
Try to add properties to your transformer:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
I think that means of properties are clear: the First to indent, the second to choose the number of spaces
Upvotes: 2