Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Read and Write JSON Files in Java?
Next article icon

How to Read and Write XML Files in Java?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

XML is defined as the Extensible Markup Language, and it is mostly used as a format for storing and exchanging data between systems. To read and write XML files, Java programming offers several easily implementable libraries. The most widely used library is the built-in JAXP (Java API for XML processing).

What is DOM?

The Document Object Model (DOM) is defined as a programming interface for web documents. In the context of XML processing in Java, DOM represents XML document as a tree model, where each node in the tree model corresponds to a part of the document. They are used to work with and navigate this tree using methods of the DOM API.

Requirements to work with XML:

  • Install the JDK (Java Development Kit) installed in your system.
  • Once installed the code into your choice either VSCode, Eclipse, or InteljIdea wherever based on your choice code editor.
  • We need to work with XML file processing and must import the javax.xml package. This package contains a parser and transforms pre-defined classes to work with XML files.

The Java API for XML Processing (JAXMP) provides a set of interfaces and classes for processing XML documents in Java programming. Here are some interfaces and classes.

  • DocumentBuilder: DocumentBuilder is a pre-defined interface in the JAXMP library that defines the methods for parsing XML documents and creating a DOM (Document Object Model) tree.
  • DocumentBuilderFactory: This class provides a factory for creating DocumentBuilder objects. It obtains the document builder instance, which is then used to parse XML documents.
  • Document: Document is an interface that offers ways to read and modify the content of an XML document while also representing the full document.
  • Element: An XML document's interface that represents an element. Elements are the fundamental units of the XML structure.
  • NodeList: An XML document's ordered collection of nodes represented by an interface that is usually used to traverse over a list of elements.
  • Transformer: An XML document transformation interface that specifies how to change the content of a Source tree into a result tree.
  • Source: An interface that can represent a stream of XML, a DOM tree, or other sources as the input for a transformation.
  • StreamResult: a class that shows the output of a straightforward transformation, usually as a character or byte stream.

Steps-by-Step Implementation

Step 1: Create the DocumentBuilder and Document

In Java Programming, we need to work with XML processing into the program. First, we create the DocumentBuilderFactory is used to accesses a DocumentBuilder instance and it instance is used to create a new Document which represents the XML structure.

 // Create a DocumentBuilder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

// Create a new Document
Document document = builder.newDocument();


Step 2: Create the root element

Once the XML document, we need to create one root element for the XML document then root element adds into the document.

// Create root element
Element root = document.createElement("library");
document.appendChild(root);

Step 3: Create child elements

Create child elements for root element add into the document using createElement and appendElement methods are used to add content into the XML document.

Step 4: Write to XML file

Write the document into the XML file using Transformer to transform the DOM structure into a stream of characters. And using StreamResult specify the output file.

Program to Write XML File in Java

Below is the code implementation to write XML files in Java Programming language.

Java
// Java Program to Write XML Using DOM Parser 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 XMLWriterExample {     public static void main(String[] args) throws Exception {         // Create a DocumentBuilder         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();         DocumentBuilder builder = factory.newDocumentBuilder();          // Create a new Document         Document document = builder.newDocument();          // Create root element         Element root = document.createElement("library");         document.appendChild(root);          // Create book elements and add text content         Element book1 = document.createElement("Program1");         book1.appendChild(document.createTextNode("Java Programming"));         Element book2 = document.createElement("Program2");         book2.appendChild(document.createTextNode("Python Programming"));         Element book3 = document.createElement("Program3");         book3.appendChild(document.createTextNode("JavaScript"));         Element book4 = document.createElement("Program4");         book4.appendChild(document.createTextNode("C Programming"));         root.appendChild(book1);         root.appendChild(book2);         root.appendChild(book3);         root.appendChild(book4);          // Write to XML file         TransformerFactory transformerFactory = TransformerFactory.newInstance();         Transformer transformer = transformerFactory.newTransformer();         DOMSource source = new DOMSource(document);          // Specify your local file path         StreamResult result = new StreamResult("C:/Users/Mahesh/Desktop/DSAˍPratice/output.xml");         transformer.transform(source, result);          System.out.println("XML file created successfully!");     } } 

Output:

XML file created successfully

Below is the generated XML File:

XML File output

Note: This example processes XML using the integrated JAXP API.

Program to Read XML File in Java

Below are the steps to implement:

  • Specify the XML file path as String and give the file location of XML file.
  • Create the DocumentBuilder and that can be used to parse the XML file.
  • After that accesses the elements using TagName.
  • Once the accesses the element using for loop then print the elements into the XML file.

XMLReaderExample.java:

Java
// Java Program to Read XML Using DOM Parser  import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import java.io.File;  public class XMLReaderExample {     public static void main(String[] args) throws Exception {         // Specify the file path as a File object         File xmlFile = new File("C:/Users/Mahesh/Desktop/DSAˍPratice/output.xml");          // Create a DocumentBuilder         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();         DocumentBuilder builder = factory.newDocumentBuilder();          // Parse the XML file         Document document = builder.parse(xmlFile);          // Access elements by tag name         NodeList nodeList = document.getElementsByTagName("library");         for (int i = 0; i < nodeList.getLength(); i++) {             Node node = nodeList.item(i);             System.out.println("Element Content: " + node.getTextContent());         }     } } 

Output:

Element Content: Java Programming python Programming JavaScript C Programming

Next Article
How to Read and Write JSON Files in Java?

M

maheshkadambala
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-Files
  • Java XML
  • Java Examples
Practice Tags :
  • Java

Similar Reads

  • How to Read and Write JSON Files in Java?
    JSON (JavaScript Object Notation) is simple but powe­rful.. It helps the server and the client to share information. Applications like­ Java use special tools, or libraries, that re­ad JSON. In Java, some libraries make it easy to read and write JSON files. One popular library is Jackson. In this ar
    4 min read
  • How to Read and Write Binary Files in Java?
    The Binary files contain data in a format that is not human-readable. To make them suitable for storing complex data structures efficiently, in Java, we can read from and write to binary files using the Input and Output Streams. In this article, we will learn and see the code implementation to read
    2 min read
  • How to Zip and Unzip Files in Java?
    In Java Programming we have a lot of features available for solving real-time problems. Here I will explain how to Zip files and How to Unzip files by using Java Programming. Mostly zip and unzip files are used for zip the files for save storage, easy to share, and other purposes. In this article, w
    3 min read
  • Java Program to Write into a File
    FileWriter class in Java is used to write character-oriented data to a file as this class is character-oriented because it is used in file handling in Java. There are many ways to write into a file in Java as there are many classes and methods which can fulfill the goal as follows: Using writeString
    6 min read
  • How to Read and Write Files Using the New I/O (NIO.2) API in Java?
    In this article, we will learn how to read and write files using the new I/O (NIO) API in Java. For this first, we need to import the file from the NIO package in Java. This NIO.2 is introduced from the Java 7 version. This provides a more efficient way of handling input and output operations compar
    3 min read
  • How to Lock a File in Java?
    In Java, file locking involves stopping processes or threads from changing a file. It comes in handy for threaded applications that require simultaneous access, to a file or to safeguard a file from modifications while it's being used by our application. When reading or writing files we need to make
    2 min read
  • How to Parse Invalid (Bad /Not Well-Formed) XML?
    Parsing invalid or not well-formed XML can be a necessity when dealing with data from diverse sources. While standard XML parsers expect well-formed XML, there are strategies and techniques to handle and extract information from malformed XML documents. In this article, we will explore how to parse
    2 min read
  • How to Serialize and Deserialize a TreeMap in Java?
    In Java, serialization is implemented by using the Serializable Interface. The use of the TreeMap class is a simple way to serialize and deserialize the objects. It is a component of the Java Collections framework. For writing and reading objects, we will be using the ObjectOutputStream and ObjectIn
    2 min read
  • How to Read a File From the Classpath in Java?
    Reading a file from the classpath concept in Java is important for Java Developers to understand. It is important because it plays a crucial role in the context of Resource Loading within applications. In Java, we can read a file from the classpath by using the Input Stream class. By loading the cla
    3 min read
  • How to Write Data into Excel Sheet using Java?
    Handling files is an important part of any programming language. Java provides various in-built methods for creating, reading, updating, and deleting files. These methods are provided by the File class which is present in the java.io package. To perform file operations, Java uses the stream class. T
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences