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.

🌐
Initial Commit
initialcommit.com › blog › how-to-read-xml-file-in-java
How to read XML file in Java
private static void parseWholeXML(Node startingNode) { NodeList childNodes = startingNode.getChildNodes(); for(int i=0; i<childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if(childNode.getNodeType() == Node.ELEMENT_NODE) { parseWholeXML(childNode); } else { // trim() is used to ignore new lines and spaces elements. if(!childNode.getTextContent().trim().isEmpty()) { System.out.println(childNode.getTextContent()); } } } } In this example, we parse the students.xml file and print out the text elements.
Discussions

How to read XML file using java - 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: More on stackoverflow.com
🌐 stackoverflow.com
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
How do i parse XML files in java ?
You could for exampel use the Jackson library to serialize and deserialise XML, you find a tutorial at https://www.baeldung.com/jackson-xml-serialization-and-deserialization More on reddit.com
🌐 r/learnjava
1
1
February 21, 2021
What's the simplest, most concise way to load an XML file from a remote server?
To get it as a String? Scanner is your one-stop io solution. It's a convenience class that was only added recently, but it makes io from any source pretty darn easy. In the header: import java.util.Scanner; import java.net.URL; In the code: Scanner in = new Scanner(new URL("www.yoursite.com")); in.useDelimiter("\\ZZZZ"); String FullText = in.next(); Then you still need to parse the xml. More on reddit.com
🌐 r/java
18
15
April 8, 2014
🌐
Mkyong
mkyong.com › home › java › how to read xml file in java – (dom parser)
How to read XML file in Java - (DOM Parser) - Mkyong.com
April 1, 2021 - This tutorial will show you how to use the Java built-in DOM parser to read an XML file.
🌐
Baeldung
baeldung.com › home › series › a guide to xml in java
A Guide to XML in Java | Baeldung
September 28, 2023 - A SAX parser is an event-based parser – it parses the XML document using callbacks without loading the whole document into memory. ... A StAX Parser is median between DOM and SAX parser.
🌐
GeeksforGeeks
geeksforgeeks.org › java › read-and-write-xml-files-in-java
How to Read and Write XML Files in Java? - GeeksforGeeks
July 27, 2025 - 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.
🌐
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 - The XML file will display under your Java project. In the same way, we can create the XML file in our local machine by using the .xml file extension. Later, we can use this XML file path in our program for parsing the XML. Let’s see the technologies for parsing the XML. XML parsing is nothing but the process of converting the XML data into a human-readable format. The XML parsing can be done by making use of different XML Parsers.
Address   TIDEL Park, 305, 3rd Floor, D-North, 4, Rajiv Gandhi Salai, Tharamani,, 600113, Chennai
Find elsewhere
🌐
Oracle
docs.oracle.com › javase › tutorial › jaxp › dom › readingXML.html
Reading XML Data into a DOM (The Java™ Tutorials > Java API for XML Processing (JAXP) > Document Object Model)
Choose one of the XML files in the data directory and run the DOMEcho program on it. Here, we have chosen to run the program on the file personal-schema.xml. % java dom/DOMEcho data/personal-schema.xml
🌐
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.
🌐
Mkyong
mkyong.com › home › java › how to read xml file in java – (jdom parser)
How to read XML file in Java – (JDOM Parser) - Mkyong.com
July 27, 2022 - The JDOM is not part of the Java built-in APIs, and we need to download the JDOM library. Maven for JDOM. ... <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency> This example shows how to use JDOM to parse an XML file.
🌐
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.
🌐
TutorialsPoint
tutorialspoint.com › java_xml › java_dom_parse_document.htm
Java DOM Parser - Parse XML Document
Having discussed various XML parsers available in Java, now let us see how we can use DOM parser to parse an XML file. We use parse() method to parse an XML file.
🌐
LabEx
labex.io › tutorials › java-read-xml-file-117444
Read XML File in Java: A Step-by-Step Guide | LabEx
In this lab, we have learned how to read an XML file using Java code. We have learned how to import required libraries, parse an XML file, iterate through each node of the root element, and extract data from each element.
🌐
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,
🌐
Inductive Automation
docs.inductiveautomation.com › ignition platform › scripting › scripting examples › parsing xml with java libraries
Parsing XML with Java Libraries | Ignition User Manual
Here's an example of how to create an XML input factory and a stream reader to parse the XML content. We iterate through the XML stream and handle different events such as starting and ending elements, as well as character data. ... from javax.xml.stream import XMLInputFactory, XMLStreamReader from java.io import ByteArrayInputStream # Create an XML input factory inputFactory = XMLInputFactory.newInstance() # Create an XML stream reader streamReader = inputFactory.createXMLStreamReader(ByteArrayInputStream(xmlString.encode())) # Iterate through the XML stream while streamReader.hasNext(): even
🌐
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
July 27, 2022 - Learn to read or parse XML documents into String, write to files and convert to POJO using Java DOM parser API with examples.
🌐
Stack Overflow
stackoverflow.com › questions › 70744724 › how-to-read-xml-file-using-java
How to read XML file using java - Stack Overflow
Reading XML files is not a trivial task by any means. It requires the reader to have intimate knowledge of the structure of the file. By that, I mean, what are the element names, the attribute names, the data type of the attributes, the order of the elements, whether the elements are simple of complex (meaning they are flat or have nested elements underneath). One solution, as shown by Jon Skeet's comment, is to use Java Document API.
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();
          }

    }
}
🌐
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
🌐
Studytonight
studytonight.com › java-examples › how-to-read-xml-file-in-java
How to read XML file in Java - Studytonight
October 15, 2023 - 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.