|
@ -0,0 +1,55 @@ |
|
|
|
|
|
package controller; |
|
|
|
|
|
|
|
|
|
|
|
import model.Person; |
|
|
|
|
|
import org.w3c.dom.Document; |
|
|
|
|
|
import org.w3c.dom.Element; |
|
|
|
|
|
|
|
|
|
|
|
import javax.xml.parsers.DocumentBuilder; |
|
|
|
|
|
import javax.xml.parsers.DocumentBuilderFactory; |
|
|
|
|
|
import javax.xml.parsers.ParserConfigurationException; |
|
|
|
|
|
import javax.xml.transform.Transformer; |
|
|
|
|
|
import javax.xml.transform.TransformerException; |
|
|
|
|
|
import javax.xml.transform.TransformerFactory; |
|
|
|
|
|
import javax.xml.transform.dom.DOMSource; |
|
|
|
|
|
import javax.xml.transform.stream.StreamResult; |
|
|
|
|
|
import java.io.*; |
|
|
|
|
|
import java.util.ArrayList; |
|
|
|
|
|
|
|
|
|
|
|
public class CreateXml { |
|
|
|
|
|
|
|
|
|
|
|
public void create(ArrayList<Person> data, File fileOut){ |
|
|
|
|
|
try { |
|
|
|
|
|
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); |
|
|
|
|
|
DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); |
|
|
|
|
|
|
|
|
|
|
|
//root elements |
|
|
|
|
|
Document doc = docBuilder.newDocument(); |
|
|
|
|
|
|
|
|
|
|
|
Element rootElement = doc.createElement("people"); |
|
|
|
|
|
doc.appendChild(rootElement); |
|
|
|
|
|
|
|
|
|
|
|
for (Person p : data) { |
|
|
|
|
|
Element person = doc.createElement("person"); |
|
|
|
|
|
rootElement.appendChild(person); |
|
|
|
|
|
|
|
|
|
|
|
//set attribute to element |
|
|
|
|
|
person.setAttribute("id", p.getId()); |
|
|
|
|
|
person.setAttribute("name", p.getName()); |
|
|
|
|
|
person.setAttribute("age", p.getAge()); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
//write the content into xml file |
|
|
|
|
|
TransformerFactory transformerFactory = TransformerFactory.newInstance(); |
|
|
|
|
|
Transformer transformer = transformerFactory.newTransformer(); |
|
|
|
|
|
DOMSource source = new DOMSource(doc); |
|
|
|
|
|
|
|
|
|
|
|
StreamResult result = new StreamResult(fileOut); |
|
|
|
|
|
transformer.transform(source, result); |
|
|
|
|
|
|
|
|
|
|
|
System.out.println("Done!"); |
|
|
|
|
|
|
|
|
|
|
|
}catch(ParserConfigurationException | TransformerException pce){ |
|
|
|
|
|
pce.printStackTrace(); |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
} |