Java XML Tutorial

Java XML Tutorial

java xml logo

In this serial of Java XML tutorials, we will show how to use the XML parser like DOM, SAX, StAX, and JDOM to read and write XML document; Also, JAXB to convert XML to/from objects.

In General, there are two programming models for working with XML documents: DOM and SAX (Streaming).

Table of contents

P.S The DOM, SAX, and StAX are part of the Java APIs.

1. Document Object Model (DOM)

The Document Object Model (DOM) uses nodes to represent the entire XML documents as a tree structure and store them in memory.

DOM is good for manipulating the small XML file, like reading, writing, and modifying the XML structure; DOM is NOT for parsing or manipulate large XML file because constructing the entire XML structure in memory will consume a lot of memory.

DOM parser examples

  1. DOM – Read XML
  2. DOM – Write XML
  3. DOM – Modify XML
  4. DOM – Pretty Print XML
  5. DOM – XML and XSLT

2. Simple API for XML (SAX)

The Simple API for XML (SAX) is a streaming model, event-driven, push-parsing API for reading XML documents (Need another API for writing). SAX reads the XML file from start to end, calls one method when it encountered one element, or calls another method when it found specific text or attribute.

The SAX is fast and efficient, requires much less memory than DOM because SAX does not create an internal representation (tree structure) of the XML data, as a DOM does.

SAX parser examples

  1. SAX – Read XML
  2. SAX – Read XML UTF-8

3. Streaming API for XML (StAX)

The Streaming API for XML (StAX) is a streaming model, event-driven, pull-parsing API for reading and writing XML documents. StAX offers a simpler programming model than SAX and more efficient memory management than DOM.

StAX parser examples

  1. StAX – Read XML
  2. StAX – Write XML

4. Third-Party XML Parser (JDOM)

The DOM, SAX, and StAX are part of the Java APIs. However, the APIs may not suit everyone’s taste. Alternatively, we can use the JDOM 2 third-party XML parsers:

JDOM parser examples

  1. JDOM – Read XML
  2. JDOM – Write XML
  3. JDOM – Modify XML

5. Java Architecture for XML Binding (JAXB)

Jakarta XML Binding (JAXB; formerly Java Architecture for XML Binding) is an XML binding framework to convert Java classes to and from XML.

JAXB examples

  1. JAXB history and hello world example

6. Java XML FAQs

Some commonly asked questions.

  1. XML External Entities (XXE)
  2. Convert XML to Properties
  3. Convert Properties to XML
  4. Count XML elements
  5. Count Depth of XML
  6. Convert String to XML

7. Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-xml

$ cd src/main/java/com/mkyong/xml/

8. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments