There are of course a lot of good solutions based on what you need. If it is just configuration, you should have a look at Jakarta commons-configuration and commons-digester.

You could always use the standard JDK method of getting a document :

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

[...]

File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
Answer from Guillaume on Stack Overflow
Top answer
1 of 10
58

There are of course a lot of good solutions based on what you need. If it is just configuration, you should have a look at Jakarta commons-configuration and commons-digester.

You could always use the standard JDK method of getting a document :

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

[...]

File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
2 of 10
40

XML Code:

<?xml version="1.0"?>
<company>
    <staff id="1001">
        <firstname>yong</firstname>
        <lastname>mook kim</lastname>
        <nickname>mkyong</nickname>
        <salary>100000</salary>
    </staff>
    <staff id="2001">
        <firstname>low</firstname>
        <lastname>yin fong</lastname>
        <nickname>fong fong</nickname>
        <salary>200000</salary>
    </staff>
</company>

Java Code:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {
    try {
    File fXmlFile = new File("/Users/mkyong/staff.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("staff");
    System.out.println("----------------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        System.out.println("\nCurrent Element :" + nNode.getNodeName());
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            System.out.println("Staff id : "
                               + eElement.getAttribute("id"));
            System.out.println("First Name : "
                               + eElement.getElementsByTagName("firstname")
                                 .item(0).getTextContent());
            System.out.println("Last Name : "
                               + eElement.getElementsByTagName("lastname")
                                 .item(0).getTextContent());
            System.out.println("Nick Name : "
                               + eElement.getElementsByTagName("nickname")
                                 .item(0).getTextContent());
            System.out.println("Salary : "
                               + eElement.getElementsByTagName("salary")
                                 .item(0).getTextContent());
        }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
  }
}

Output:

----------------

Root element :company
----------------------------

Current Element :staff
Staff id : 1001
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000

Current Element :staff
Staff id : 2001
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

I recommended you reading this: Normalization in DOM parsing with java - how does it work?

Example source.

Discussions

Is there an easy way to read an XML file in Java? - Stack Overflow
I'm fairly new to Java and am writing ... config file. The problem I have is that there doesn't seem to be any easy way to do this, which seems a bit strange. I've looked SAX and DOM and both seem quite complicated. Are there any other good API's out there? What's the best way to do this in Java? Thanks... ... Many dupes. Here's a recent one with a nicely formatted question: stackoverflow.com/questions/2333479/โ€ฆ ... There are many XML api to read XML, see this ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 27, 2022
Java - Reading XML file - Stack Overflow
I am trying to read in some data from an XML file and having some trouble, the XML I have is as follows: tes... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How to read and write XML files? - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I have to read and write to and from an XML file. What is the easiest way to read and write XML files using Java? More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to read an XML file with Java? - Stack Overflow
I don't need to read complex XML files. I just want to read the following configuration file with a simplest XML reader localhost More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 9, 2009
๐ŸŒ
Initial Commit
initialcommit.com โ€บ blog โ€บ how-to-read-xml-file-in-java
How to read XML file in Java
File xmlFile = new File("students.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile);
๐ŸŒ
javathinking
javathinking.com โ€บ blog โ€บ how-to-read-and-write-xml-files
How to Read and Write XML Files in Java: The Easiest Way Explained โ€” javathinking.com
DOM Parser: Best for small XML files when you need to manually traverse or manipulate the XML structure. JAXB: Ideal for mapping XML to Java objects, reducing boilerplate and errors.
๐ŸŒ
Edureka
edureka.co โ€บ blog โ€บ java-xml-parser
Java XML Parser | Read and Parse XML File in Java | Edureka
April 29, 2024 - This article on java XML parser will help you understand what an XML parser is and how to parse an XML file using dom parser in Java.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ how-to-read-xml-file-in-java
How to Read XML File in Java - Javatpoint
How to Read XML File in Java with oops, string, exceptions, multithreading, collections, jdbc, rmi, fundamentals, programs, swing, javafx, io streams, networking, sockets, classes, objects etc,
Find elsewhere
๐ŸŒ
GitHub
github.com โ€บ RameshMF โ€บ java-xml-tutorial
GitHub - RameshMF/java-xml-tutorial: Tutorial to parse or processing xml file in Java with different XML Parsers ยท GitHub
DOM Parser is the easiest Java XML parser to learn. DOM parser loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes ...
Starred by 4 users
Forked by 3 users
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-extract-content-from-a-xml-document
Java Program to Extract Content From a XML Document - GeeksforGeeks
July 23, 2025 - Java DOM Parser: DOM stands for Document Object Model. The DOM API provides the classes to read and write an XML file. DOM reads an entire document. It is useful when reading small to medium size XML files. It is a tree-based parser and a little slow when compared to SAX and occupies more space when loaded into memory.
๐ŸŒ
Codoid
codoid.com โ€บ automation-testing โ€บ read-data-from-xml-by-using-different-parsers-in-java
Read Data from XML by Using Different Parsers in Java - Codoid
September 18, 2024 - Instead, it triggers events when it encounters the opening tag, closing tag, and character data in an XML file. It reads the XML from top to bottom and identifies the tokens and call-back methods in the handler that are invoked. Due to the top to bottom approach, tokens are parsed in the same order as they appear in the document. Due to the change in the way SAX works, it is faster and uses less memory in comparison to the DOM parser.
Call ย  1800 (212) 6988
Address ย  TIDEL Park, 305, 3rd Floor, D-North, 4, Rajiv Gandhi Salai, Tharamani,, 600113, Chennai
Top answer
1 of 4
60

One of the possible implementations:

File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

2 of 4
6

Reading xml the easy way:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

          } catch (JAXBException e) {
              e.printStackTrace();
          }

    }
}
Top answer
1 of 7
145

Here is a quick DOM example that shows how to read and write a simple xml file with its dtd:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE roles SYSTEM "roles.dtd">
<roles>
    <role1>User</role1>
    <role2>Author</role2>
    <role3>Admin</role3>
    <role4/>
</roles>

and the dtd:

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT roles (role1,role2,role3,role4)>
<!ELEMENT role1 (#PCDATA)>
<!ELEMENT role2 (#PCDATA)>
<!ELEMENT role3 (#PCDATA)>
<!ELEMENT role4 (#PCDATA)>

First import these:

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;

Here are a few variables you will need:

private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList<String> rolev;

Here is a reader (String xml is the name of your xml file):

public boolean readXML(String xml) {
        rolev = new ArrayList<String>();
        Document dom;
        // Make an  instance of the DocumentBuilderFactory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // use the factory to take an instance of the document builder
            DocumentBuilder db = dbf.newDocumentBuilder();
            // parse using the builder to get the DOM mapping of the    
            // XML file
            dom = db.parse(xml);

            Element doc = dom.getDocumentElement();

            role1 = getTextValue(role1, doc, "role1");
            if (role1 != null) {
                if (!role1.isEmpty())
                    rolev.add(role1);
            }
            role2 = getTextValue(role2, doc, "role2");
            if (role2 != null) {
                if (!role2.isEmpty())
                    rolev.add(role2);
            }
            role3 = getTextValue(role3, doc, "role3");
            if (role3 != null) {
                if (!role3.isEmpty())
                    rolev.add(role3);
            }
            role4 = getTextValue(role4, doc, "role4");
            if ( role4 != null) {
                if (!role4.isEmpty())
                    rolev.add(role4);
            }
            return true;

        } catch (ParserConfigurationException pce) {
            System.out.println(pce.getMessage());
        } catch (SAXException se) {
            System.out.println(se.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }

        return false;
    }

And here a writer:

public void saveToXML(String xml) {
    Document dom;
    Element e = null;

    // instance of a DocumentBuilderFactory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        // use factory to get an instance of document builder
        DocumentBuilder db = dbf.newDocumentBuilder();
        // create instance of DOM
        dom = db.newDocument();

        // create the root element
        Element rootEle = dom.createElement("roles");

        // create data elements and place them under root
        e = dom.createElement("role1");
        e.appendChild(dom.createTextNode(role1));
        rootEle.appendChild(e);

        e = dom.createElement("role2");
        e.appendChild(dom.createTextNode(role2));
        rootEle.appendChild(e);

        e = dom.createElement("role3");
        e.appendChild(dom.createTextNode(role3));
        rootEle.appendChild(e);

        e = dom.createElement("role4");
        e.appendChild(dom.createTextNode(role4));
        rootEle.appendChild(e);

        dom.appendChild(rootEle);

        try {
            Transformer tr = TransformerFactory.newInstance().newTransformer();
            tr.setOutputProperty(OutputKeys.INDENT, "yes");
            tr.setOutputProperty(OutputKeys.METHOD, "xml");
            tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
            tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            // send DOM to file
            tr.transform(new DOMSource(dom), 
                                 new StreamResult(new FileOutputStream(xml)));

        } catch (TransformerException te) {
            System.out.println(te.getMessage());
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }
    } catch (ParserConfigurationException pce) {
        System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
    }
}

getTextValue is here:

private String getTextValue(String def, Element doc, String tag) {
    String value = def;
    NodeList nl;
    nl = doc.getElementsByTagName(tag);
    if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
        value = nl.item(0).getFirstChild().getNodeValue();
    }
    return value;
}

Add a few accessors and mutators and you are done!

2 of 7
17

Writing XML using JAXB (Java Architecture for XML Binding):

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

          } catch (JAXBException e) {
        e.printStackTrace();
          }

    }
}
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ read-and-write-xml-files-in-java
How to Read and Write XML Files in Java? - GeeksforGeeks
July 27, 2025 - 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.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ series โ€บ a guide to xml in java
A Guide to XML in Java | Baeldung
September 28, 2023 - JAXB is a part of the Java SE platform and one of the APIs in Jakarta EE. ... XStream is a simple library to serialize objects to/from XML. ... Jackson XML is an extension of the Jackson JSON processor for reading and writing XML encoded data.
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ java xml โ€บ read an xml file using dom parser in java
Read an XML File using DOM Parser in Java
March 5, 2018 - Learn to read or parse XML documents into String, write to files and convert to POJO using Java DOM parser API with examples.
๐ŸŒ
Quora
quora.com โ€บ How-do-we-read-an-XML-file-using-Java-code-XML-Parser
How do we read an XML file using Java code (XML Parser)? - Quora
Discover instant and clever code completion, on-the-fly code analysis, and reliable refactoring tools. ... There are 2 major types of parsing for XML Dom and sax. There is one more Stax parser.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2011 โ€บ 12 โ€บ parse-xml-file-in-java-example-tutorial.html
How to Parse or Read XML File in Java >> XML Tutorial Example
Here are a couple of ways to parse an XML file in Java. You will learn how to use JAXP and DOM parser to load the XML file in Java ยท Java provides extensive support for reading XML file, writing XML file and accessing any element from XML file. All XML parsing related classes and methods are inside JAXP.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2015 โ€บ 07 โ€บ how-to-read-xml-file-as-string-in-java-example.html
How to Read XML File as String in Java? 3 Examples
April 28, 2025 - In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.
๐ŸŒ
Studytonight
studytonight.com โ€บ java-examples โ€บ how-to-read-xml-file-in-java
How to read XML file in Java - Studytonight
In this tutorial we will learn to read an XML file in Java, Java provides an XML parser library that is helpful to read and write the XML document.