All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Create XML File In Java

Last Updated : Mar 11, 2024

How To Create XML File In Java

In this article we will show you the solution of how to create xml file in java, you must be familiar with the fundamentals of XML and make use of Java's XML processing capabilities in order to generate an XML file in the language.

A widely adopted standard for storing and transferring structured data is XML (eXtensible Markup Language).

A few steps in Java can be used to build an XML file. First, import the required XML libraries, such as SAX or DOM (Simple API for XML).

These libraries include classes and XML manipulation methods. Initialise a Document object next, which stands in for the root element of the XML file.

Using the classes and methods offered, you can then create child components, attributes, and text nodes.

After the XML structure has been established, add child elements, give attributes and text nodes values, and then fill it with data.

The XML tree can be explored and the elements can be adjusted as necessary. Now we'll talk about how to build an XML file in Java.

Step By Step Guide On How To Create XML File In Java :-

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class CreateXMLFile {
    public static void main(String[] args) {
        try {
            // Create a new DocumentBuilder
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            // Create a new Document
            Document document = builder.newDocument();
            // Create the root element
            Element rootElement = document.createElement("Employees");
            document.appendChild(rootElement);
            // Create employee elements
            Element employee1 = createEmployeeElement(document, "Madan Rai", "Engineer");
            rootElement.appendChild(employee1);
            Element employee2 = createEmployeeElement(document, "Chandan Rai", "Manager");
            rootElement.appendChild(employee2);
            // Write the document to XML file
            File xmlFile = new File("employees.xml");
            OutputStream outStream = new FileOutputStream(xmlFile);
            TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(outStream));
            System.out.println("XML file created successfully.");
        } catch (ParserConfigurationException | TransformerException | IOException e) {
            e.printStackTrace();
        }
    }
    private static Element createEmployeeElement(Document document, String name, String designation) {
        Element employee = document.createElement("Employee");
        // Create name element
        Element nameElement = document.createElement("Name");
        Text nameText = document.createTextNode(name);
        nameElement.appendChild(nameText);
        employee.appendChild(nameElement);
        // Create designation element
        Element designationElement = document.createElement("Designation");
        Text designationText = document.createTextNode(designation);
        designationElement.appendChild(designationText);
        employee.appendChild(designationElement);
        return employee;
    }
}
  1. We start by importing the necessary classes and packages for XML.
  2. We specify the main method of the CreateXMLFile class, which serves as the execution entry point.
  3. We utilize a try-catch block inside the main method to deal with any exceptions that might arise while creating the XML.
  4. We build a new DocumentBuilderFactory to produce a DocumentBuilder object inside the try block.
  5. New instances of the Document are made by the DocumentBuilder.
  6. Using the newDocument() function of the DocumentBuilder, a new Document object is created. This is a representation of the XML file that will be created.
  7. Using the Document object's createElement() method, we create the root element, Employees.
  8. We use the appendChild() method to append it to the document.
  9. Using the Document object and the employee details (name and designation) as arguments, we construct two employee elements using the createEmployeeElement() method.
  10. These employee elements are added to the root element.
  11. Using nested name & designation components, the createEmployeeElement() function constructs an employee element. The employee element is returned.
  12. Using FileOutputStream and TransformerFactory, we output the XML file to a file called employees.xml.
  13. The transformation's input source is represented by the DOMSource, and its output target is by the StreamResult.
  14. If the creation of the XML file is successful, we print a success message. In the event that an exception arises, we capture it and print it to the console.

Conclusion :-

As a result, we have successfully mastered the Java notion of creating an XML file.

We also discovered that using Java's XML processing libraries and comprehending XML principles are required in order to produce an XML file.

With this information, creating XML files in Java for the storage and exchange of structured data is simple and efficient.

I hope this article on how to create xml file in java helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Dikshita

Passionate Electronics and Communication Engineering student with expertise in web development (HTML, CSS, JS,PHP, Bootstrap, React.js) and content writing. Eager problem solver and tech enthusiast, adept at creating engaging web experiences.

Follow Dikshita On Linkedin 🡪