Actually Java supports 4 methods to parse XML out of the box:

DOM Parser/Builder: The whole XML structure is loaded into memory and you can use the well known DOM methods to work with it. DOM also allows you to write to the document with Xslt transformations. Example:

Copypublic static void parse() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    File file = new File("test.xml");
    Document doc = builder.parse(file);
    // Do something with the document here.
}

SAX Parser: Solely to read a XML document. The Sax parser runs through the document and calls callback methods of the user. There are methods for start/end of a document, element and so on. They're defined in org.xml.sax.ContentHandler and there's an empty helper class DefaultHandler.

Copypublic static void parse() throws ParserConfigurationException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser saxParser = factory.newSAXParser();
    File file = new File("test.xml");
    saxParser.parse(file, new ElementHandler());    // specify handler
}

StAx Reader/Writer: This works with a datastream oriented interface. The program asks for the next element when it's ready just like a cursor/iterator. You can also create documents with it. Read document:

Copypublic static void parse() throws XMLStreamException, IOException {
    try (FileInputStream fis = new FileInputStream("test.xml")) {
        XMLInputFactory xmlInFact = XMLInputFactory.newInstance();
        XMLStreamReader reader = xmlInFact.createXMLStreamReader(fis);
        while(reader.hasNext()) {
            reader.next(); // do something here
        }
    }
}

Write document:

Copypublic static void parse() throws XMLStreamException, IOException {
    try (FileOutputStream fos = new FileOutputStream("test.xml")){
        XMLOutputFactory xmlOutFact = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = xmlOutFact.createXMLStreamWriter(fos);
        writer.writeStartDocument();
        writer.writeStartElement("test");
        // write stuff
        writer.writeEndElement();
    }
}

JAXB: The newest implementation to read XML documents: Is part of Java 6 in v2. This allows us to serialize java objects from a document. You read the document with a class that implements a interface to javax.xml.bind.Unmarshaller (you get a class for this from JAXBContext.newInstance). The context has to be initialized with the used classes, but you just have to specify the root classes and don't have to worry about static referenced classes. You use annotations to specify which classes should be elements (@XmlRootElement) and which fields are elements(@XmlElement) or attributes (@XmlAttribute, what a surprise!)

Copypublic static void parse() throws JAXBException, IOException {
    try (FileInputStream adrFile = new FileInputStream("test")) {
        JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
        Unmarshaller um = ctx.createUnmarshaller();
        RootElementClass rootElement = (RootElementClass) um.unmarshal(adrFile);
    }
}

Write document:

Copypublic static void parse(RootElementClass out) throws IOException, JAXBException {
    try (FileOutputStream adrFile = new FileOutputStream("test.xml")) {
        JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
        Marshaller ma = ctx.createMarshaller();
        ma.marshal(out, adrFile);
    }
}

Examples shamelessly copied from some old lecture slides ;-)

Edit: About "which API should I use?". Well it depends - not all APIs have the same capabilities as you see, but if you have control over the classes you use to map the XML document JAXB is my personal favorite, really elegant and simple solution (though I haven't used it for really large documents, it could get a bit complex). SAX is pretty easy to use too and just stay away from DOM if you don't have a really good reason to use it - old, clunky API in my opinion. I don't think there are any modern 3rd party libraries that feature anything especially useful that's missing from the STL and the standard libraries have the usual advantages of being extremely well tested, documented and stable.

Answer from Voo on Stack Overflow
Top answer
1 of 7
238

Actually Java supports 4 methods to parse XML out of the box:

DOM Parser/Builder: The whole XML structure is loaded into memory and you can use the well known DOM methods to work with it. DOM also allows you to write to the document with Xslt transformations. Example:

Copypublic static void parse() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    File file = new File("test.xml");
    Document doc = builder.parse(file);
    // Do something with the document here.
}

SAX Parser: Solely to read a XML document. The Sax parser runs through the document and calls callback methods of the user. There are methods for start/end of a document, element and so on. They're defined in org.xml.sax.ContentHandler and there's an empty helper class DefaultHandler.

Copypublic static void parse() throws ParserConfigurationException, SAXException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser saxParser = factory.newSAXParser();
    File file = new File("test.xml");
    saxParser.parse(file, new ElementHandler());    // specify handler
}

StAx Reader/Writer: This works with a datastream oriented interface. The program asks for the next element when it's ready just like a cursor/iterator. You can also create documents with it. Read document:

Copypublic static void parse() throws XMLStreamException, IOException {
    try (FileInputStream fis = new FileInputStream("test.xml")) {
        XMLInputFactory xmlInFact = XMLInputFactory.newInstance();
        XMLStreamReader reader = xmlInFact.createXMLStreamReader(fis);
        while(reader.hasNext()) {
            reader.next(); // do something here
        }
    }
}

Write document:

Copypublic static void parse() throws XMLStreamException, IOException {
    try (FileOutputStream fos = new FileOutputStream("test.xml")){
        XMLOutputFactory xmlOutFact = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = xmlOutFact.createXMLStreamWriter(fos);
        writer.writeStartDocument();
        writer.writeStartElement("test");
        // write stuff
        writer.writeEndElement();
    }
}

JAXB: The newest implementation to read XML documents: Is part of Java 6 in v2. This allows us to serialize java objects from a document. You read the document with a class that implements a interface to javax.xml.bind.Unmarshaller (you get a class for this from JAXBContext.newInstance). The context has to be initialized with the used classes, but you just have to specify the root classes and don't have to worry about static referenced classes. You use annotations to specify which classes should be elements (@XmlRootElement) and which fields are elements(@XmlElement) or attributes (@XmlAttribute, what a surprise!)

Copypublic static void parse() throws JAXBException, IOException {
    try (FileInputStream adrFile = new FileInputStream("test")) {
        JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
        Unmarshaller um = ctx.createUnmarshaller();
        RootElementClass rootElement = (RootElementClass) um.unmarshal(adrFile);
    }
}

Write document:

Copypublic static void parse(RootElementClass out) throws IOException, JAXBException {
    try (FileOutputStream adrFile = new FileOutputStream("test.xml")) {
        JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
        Marshaller ma = ctx.createMarshaller();
        ma.marshal(out, adrFile);
    }
}

Examples shamelessly copied from some old lecture slides ;-)

Edit: About "which API should I use?". Well it depends - not all APIs have the same capabilities as you see, but if you have control over the classes you use to map the XML document JAXB is my personal favorite, really elegant and simple solution (though I haven't used it for really large documents, it could get a bit complex). SAX is pretty easy to use too and just stay away from DOM if you don't have a really good reason to use it - old, clunky API in my opinion. I don't think there are any modern 3rd party libraries that feature anything especially useful that's missing from the STL and the standard libraries have the usual advantages of being extremely well tested, documented and stable.

2 of 7
13

Java supports two methods for XML parsing out of the box.

SAXParser

You can use this parser if you want to parse large XML files and/or don't want to use a lot of memory.

http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html

Example: http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

DOMParser

You can use this parser if you need to do XPath queries or need to have the complete DOM available.

http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilderFactory.html

Example: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

🌐
Baeldung
baeldung.com › home › xml › xml libraries support in java
XML Libraries Support in Java
June 20, 2025 - In Java XML support we can find few API definitions, each one has its pros and cons. • SAX: It is an event based parsing API, it provides a low level access, is memory efficient and faster than DOM since it doesn’t load the whole document tree in memory but it doesn’t provide support for navigation like the one provided by XPath, although it is more efficient it is harder to use too. • DOM: It as model based parser that loads a tree structure document in memory, so we have the original elements order, we can navigate our document both directions, it provides an API for reading and writing, it offers XML manipulation and it is very easy to use although the price is high strain on memory resources.
Discussions

What are some well maintained XML libraries?
JAXB. Jackson. If support for either of those is dropped then a large percentage of systems are screwed. More on reddit.com
🌐 r/java
25
25
April 8, 2024
Best Java JSON Parser: Gson or Jackson?

Jackson, but mostly because I tend to use it from Spring MVC and it just works without any extra effort.

More on reddit.com
🌐 r/java
61
47
February 21, 2014
What is the best way to parse and munipulate large XML files in Java
As stated in another comment....sax is probably the best place to start assuming the XML file you have is just something you have created. If the XML you are importing has a schema associated with it...you could also use JAXB http://www.oracle.com/technetwork/articles/javase/index-140168.html . This allows you to generate java classes to work with your XML file. Regarding the best way to structure a java project...check out Maven. Its a great tool for creating projects with a well known structure. More on reddit.com
🌐 r/java
14
4
July 8, 2012
Best XML Parser for simple XML reading.
Memory consumption is only usually a problem with large XML files; yours would be fine. More on reddit.com
🌐 r/androiddev
11
4
March 29, 2011
🌐
TutorialsPoint
tutorialspoint.com › home › java_xml › java xml parsers
Java XML Parsers
September 1, 2008 - We can read, create, query and modify the XML documents using these APIs. APIs provide interfaces that represent the XML documents, methods to retrieve and modify the elements and attributes in XML documents. XML Parsers are the software libraries ...
🌐
Oracle
docs.oracle.com › cd › E28280_01 › appdev.1111 › b28394 › adx_j_parser.htm
4 XML Parsing for Java
For example, change into the $ORACLE_HOME/xdk/demo/java/parser/common directory. You can validate the document family.xml against family.dtd by executing the following on the command line: ... The encoding of the input file: UTF-8The input XML file is parsed without errors using DTD validation mode. The W3C standard library org.w3c.dom defines the Document class as well as classes for the components of a DOM.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-xml-parsers-1
Java XML Parsers - GeeksforGeeks
June 27, 2024 - The DOM parser is good when working with an XML in-memory setup; the SAX parser works well within a low-memory, high-performance environment; and the StAX parser, appropriate for a good balance between the two, will keep you in control of the ...
🌐
GitHub
github.com › rkalla › simple-java-xml-parser
GitHub - rkalla/simple-java-xml-parser: Java XML parser with XPath's ease-of-use and pull-parsing performance. Built for use on Android, web services, web applications or client-side Java. · GitHub
Description ----------- A very small (4 classes) abstraction layer that sits on top of the XML Pull Parser spec (http://xmlpull.org/) to provide a namespace-capable XML Parser with the ease-of-use of XPath with the performance of a native pull parser. SJXP was designed to work on any Java platform, including Android 1.5+. This library supports parsing 2 types of data from an XML source: * Character data (text between tags) * Attribute values Parsing rules (IRule instances) are defined as a series of XPath-esque "location paths" pointing at elements or attribute names, for example the following
Starred by 38 users
Forked by 20 users
Languages   Java
Find elsewhere
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › javax › xml › parsers › package-summary.html
javax.xml.parsers (Java Platform SE 8 )
October 20, 2025 - Java™ Platform Standard Ed. 8 ... Provides classes allowing the processing of XML documents. ... Provides classes allowing the processing of XML documents. Two types of plugable parsers are supported:
🌐
Inductive Automation
docs.inductiveautomation.com › ignition platform › scripting › scripting examples › parsing xml with java libraries
Parsing XML with Java Libraries | Ignition User Manual
The Streaming API for XML (StAX) parser, available through Java libraries, offers a cursor-based approach to parse XML documents. It provides an efficient way to read and process XML sequentially without loading the entire document into memory. StAX parsers allow developers to iterate through ...
🌐
Java-source
java-source.net › open-source › xml-parsers
Open Source XML Parsers in Java
Go To Piccolo XML Parser · Go To JiBX: Binding XML to Java Code
🌐
Medium
sekarbala.medium.com › java-xml-parsers-c5467e2dc2e1
Java XML Parsers. In Java, there are several types of XML… | by Balasekar Natarajan | Medium
November 2, 2024 - How it works: Loads the entire XML document into memory and creates a tree structure representing the XML document. Use cases: Useful when you need to access different parts of the XML multiple times or when the structure needs to be manipulated.
🌐
GitHub
github.com › codemonstur › simplexml
GitHub - codemonstur/simplexml: A standalone Java XML parser and serializer
A standalone Java XML parser and serializer. Contribute to codemonstur/simplexml development by creating an account on GitHub.
Starred by 23 users
Forked by 3 users
Languages   Java 99.3% | Makefile 0.7% | Java 99.3% | Makefile 0.7%
🌐
Apache Commons
commons.apache.org › proper › commons-jelly › apidocs › org › apache › commons › jelly › parser › XMLParser.html
XMLParser
The SAXParser and XMLReader portions of this code come from Digester. Version: $Revision: 1807798 $ Author: James Strachan · private static java.util.Properties jellyProperties · Share the Jelly properties across parsers · private JellyContext context · JellyContext which is used to locate tag libraries ·
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › javax › xml › parsers › package-summary.html
javax.xml.parsers (Java Platform SE 7 )
Java™ Platform Standard Ed. 7 ... Provides classes allowing the processing of XML documents. ... Provides classes allowing the processing of XML documents. Two types of plugable parsers are supported:
🌐
Coderanch
coderanch.com › t › 624791 › languages › Library-XML-parsing
Best Library for XML parsing (XML forum at Coderanch)
If you intend to make use of just a subset of the XML, then I wouldn't recommend either DOM or JAXB. Besides XPath, other alternatives that are also part of the JRE are the SAX and StAX APIs. Plus, there are 3rd party libraries like XOM, JDOM and dom4j, but if the aim is merely to read, then I probably wouldn't use those. ... Without any more details, I am going to suggest something simple. Use the DOM parser and XPATH - XPATH needs a DOM to work with so your first step will be learning how to get a DOM into memory.
🌐
Baeldung
baeldung.com › home › series › a guide to xml in java
A Guide to XML in Java | Baeldung
September 28, 2023 - ... JAXB – Java Architecture for XML Binding – is used to convert objects from/to XML. 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.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-xml-parser
Java XML Parser | DigitalOcean
August 4, 2022 - JDOM provides a great Java XML parser API to read, edit and write XML documents easily. JDOM provides wrapper classes to chose your underlying implementation from SAX Parser, DOM Parser, STAX Event Parser and STAX Stream Parser.
🌐
Edureka
edureka.co › blog › java-xml-parser
Java XML Parser | Read and Parse XML File in Java | Edureka
April 29, 2024 - In this article, let’s explore Java XML Parser in detail. ... The XML parser is a software library or a package that provides an interface for client applications to work with XML documents.
🌐
TutorialsPoint
tutorialspoint.com › java_xml › java_dom_parse_document.htm
Java DOM Parser - Parse XML Document
import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; public class RetrieveRootElementName { public static void main(String[] args) { try { //Creating a DocumentBuilder Object DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Reading the XML StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append("<college></college>"); //Parsing the XML Document ByteArrayInputStream input =