Creating XML file in Java from array

In this post I describe you how creating XML file. XML will be contain data from array. Data will be present information about persons from company.

Let’s create XMLCreate project.

In tree of project You see XMLCreate main class.

For this project create class which will be getting data form array and write them into xml file. So cright click on project node and choose New->Java Class. In Class Name field write CreateNewXML and select from Package list our net.doraprojects package.

Click the Finish button. Create another class: Person in the same way as this before.

Into Person class paste this code:


package net.doraprojects;

public class Person 
{
    int id = 0;
    String firstname = null;
    String surname = null;
    String profession = null;
    
    public Person(int id, String firstname, String surname, String profession)
    {
     this.id = id;  
     this.firstname = firstname;
     this.surname = surname;
     this.profession = profession;
    }
    
    public int getId()
    {
        return id;
    }
     public String getFirstname()
    {
        return firstname;
    }
      public String getSurname()
    {
        return surname;
    }
       public String getProfession()
    {
        return profession;
    }
}

 

Into CreateNewXML.java file paste this code:


package net.doraprojects;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateNewXML 
{       
    public CreateNewXML()
   {
    Person person1 = new Person(12,"Kate","Muller","teacher");
    Person person2 = new Person(10,"Bill","Yung","musician");
    Person person3 = new Person(134,"Olaf","Roy","engineer");
    Person person4 = new Person(2,"Iga","Suly","shopkeeper");
    Person person5 = new Person(23,"Nancy","Caty","sailor");
    
    Person[] tab = new Person[] { person1, person2, person3, person4, person5 };
       try 
       { 
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       DocumentBuilder builder = factory.newDocumentBuilder();
       Document doc = builder.newDocument();
       doc.setXmlStandalone(true);
       Element rootElement = doc.createElement("employees");
       doc.appendChild(rootElement);
       for(int i=0; i