|
|
@ -0,0 +1,47 @@ |
|
|
|
package com.jorpelu; |
|
|
|
|
|
|
|
import java.io.File; |
|
|
|
import java.util.ArrayList; |
|
|
|
|
|
|
|
import javax.xml.parsers.*; |
|
|
|
import javax.xml.transform.*; |
|
|
|
import javax.xml.transform.dom.DOMSource; |
|
|
|
import javax.xml.transform.stream.StreamResult; |
|
|
|
|
|
|
|
import org.w3c.dom.Attr; |
|
|
|
import org.w3c.dom.Document; |
|
|
|
import org.w3c.dom.Element; |
|
|
|
|
|
|
|
public class EscribirXML { |
|
|
|
public EscribirXML(ArrayList<Persona> personasList) { |
|
|
|
try { |
|
|
|
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); |
|
|
|
DocumentBuilder db = dbf.newDocumentBuilder(); |
|
|
|
Document doc = db.newDocument(); |
|
|
|
|
|
|
|
Element eRaiz = doc.createElement("personas"); |
|
|
|
doc.appendChild(eRaiz); |
|
|
|
for(int i = 0; i<personasList.size(); i++) { |
|
|
|
Element ePersona = doc.createElement("persona"); |
|
|
|
eRaiz.appendChild(ePersona); |
|
|
|
|
|
|
|
Element eNombre = doc.createElement("nombre"); |
|
|
|
eNombre.appendChild(doc.createTextNode(personasList.get(i).getNombre())); |
|
|
|
ePersona.appendChild(eNombre); |
|
|
|
|
|
|
|
Element eEdad = doc.createElement("edad"); |
|
|
|
eEdad.appendChild(doc.createTextNode(String.valueOf(personasList.get(i).getEdad()))); |
|
|
|
ePersona.appendChild(eEdad); |
|
|
|
} |
|
|
|
TransformerFactory transformerFactory = TransformerFactory.newInstance(); |
|
|
|
Transformer transformer = transformerFactory.newTransformer(); |
|
|
|
DOMSource source = new DOMSource(doc); |
|
|
|
StreamResult result = new StreamResult(new File("personas.xml")); |
|
|
|
transformer.transform(source, result); |
|
|
|
|
|
|
|
}catch (Exception e) { |
|
|
|
System.out.println("Error al escribir el .xml"); |
|
|
|
e.getLocalizedMessage(); |
|
|
|
} |
|
|
|
} |
|
|
|
} |