All TalkersCode Topics

Follow TalkersCode On Social Media

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

Read And Write XML File In Java

Last Updated : Mar 11, 2024

Read And Write XML File In Java

In this article we ill show you the solution of read and write xml file in java, java XML APIs like DOM, SAX, and StAX are used to read and write XML files. Tags are used in XML files to specify elements and organise data.

A suitable API must be chosen, a parser instance must be created, the XML file must be provided as input, and the needed data must be extracted by either traversing the XML structure or handling events.

A new or modified XML document that has elements, attributes, and data added is serialised to a file or output stream after being given the desired API.

Java provides libraries like JAXP to make parsing XML simpler. Due to their hierarchical structure and human-readable syntax, XML files are frequently used for storing and sending data between computers.

The efficient processing & retrieval of data from XML files is made possible via Java's XML APIs. Additionally, we now understand how to read and write XML files in Java.

Step By Step Guide On Read And Write Xml File In Java :-

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class XMLReadWriteExample {
    public static void main(String[] args) {
        // Reading XML file
        readXMLFile("input.xml");
        // Writing XML file
        writeXMLFile("output.xml");
    }
    public static void readXMLFile(String filename) {
        try {
            // Create a DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // Create a DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new File(filename));
            // Normalize the document
            document.getDocumentElement().normalize();
            // Get the root element
            Element rootElement = document.getDocumentElement();
            System.out.println("Root Element: " + rootElement.getNodeName());
            // Get child nodes
            NodeList nodeList = rootElement.getChildNodes();
            // Iterate over child nodes
            for (int p = 0; p < nodeList.getLength(); p++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    String data = element.getTextContent();
                    System.out.println("Elements: " + element.getNodeName() + ", Data: " + data);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  1. We import the essential classes from the org.w3c.dom and javax.xml.parsers packages for working with XML files using the import statements at the beginning of the code.
  2. The XMLReadWriteExample class includes two methods, which are readXMLFile and writeXMLFile.
  3. We call readXMLFile("input.xml") and writeXMLFile("output.xml") in the main method to read and write respective XML files, respectively.
  4. A filename is a required parameter for the readXMLFile function. In order to generate a DocumentBuilder, we create an instance of DocumentBuilderFactory.
  5. The XML file supplied by the filename is parsed by the DocumentBuilder to produce a Document object that represents the XML structure.
  6. To make sure the XML structure is consistent, we call the normalise method on the Document.
  7. The root element of the XML document is retrieved using the getDocumentElement function.
  8. To obtain a list of the root element's child nodes, use the getChildNodes function.
  9. We iterate through the child nodes in the for loop. Using the getNodeType method, we determine for each node whether it is an element node.
  10. If so, we use the getTextContent method to extract the text content by casting the node to an Element. The element name & its associated data are then printed.
  11. The filename is a parameter for the writeXMLFile function. It follows the same procedures as the readXMLFile method, except that we produce a new XML document rather than reading one.
  12. To build elements and text nodes, respectively, we can utilise methods like createElement and createTextNode.
  13. AppendChild and other similar techniques are used to add the items to the document structure.
  14. Finally, we use classes like TransformerFactory, Transformer, as well as DOMSource to serialise the document to a file.
  15. Using e.printStackTrace(), any exceptions that arise while reading or writing are captured and printed.

Conclusion :-

As a result, we were able to master the Java idea of reading and writing XML files.

We also discovered that because of their human-readable format and hierarchical structure, XML files are commonly employed for data storage and interchange.

The efficient processing and retrieval of data from XML files is made possible via Java's XML APIs.

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

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪