XML Processing
Java provides several APIs for processing XML: DOM (Document Object Model — loads the entire document into memory), SAX (Simple API for XML — event-based, streaming), StAX (Streaming API for XML — pull parsing), and JAXB (Java Architecture for XML Binding — marshal/unmarshal Java objects to XML).
DOM is a good fit for small documents that need to be modified. SAX is a good fit for large documents because it is memory efficient (streaming). StAX gives the programmer more control. JAXB makes automatic conversion between Java objects and XML easy, using annotations.
Java 9+ supports XPath and XSLT transformations built in. DocumentBuilder and Transformer are the main classes for parsing and transforming XML.
XML Processing APIs:
| API | Approach | Use |
|---|---|---|
| DOM | Tree-based | Small documents, need modification |
| SAX | Event-based | Large documents, memory efficient |
| StAX | Pull-based | Streaming control |
| JAXB | Binding | Objects ↔ XML automatically |
Code Example
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import java.io.*;
public class XMLJava {
public static void main(String[] args) throws Exception {
// Create XML with DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
// Root element
Element root = doc.createElement("library");
doc.appendChild(root);
// Add books
addBook(doc, root, "Bumi", "Tere Liye", 2014);
addBook(doc, root, "Laskar Pelangi", "Andrea Hirata", 2005);
// Save to file
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(doc),
new StreamResult(new File("library.xml")));
System.out.println("XML created successfully.");
// Read XML
Document doc2 = builder.parse(new File("library.xml"));
NodeList bookList = doc2.getElementsByTagName("book");
for (int i = 0; i < bookList.getLength(); i++) {
Element book = (Element) bookList.item(i);
System.out.printf("Title: %s | Author: %s | Year: %s%n",
book.getAttribute("title"),
book.getAttribute("author"),
book.getAttribute("year"));
}
}
static void addBook(Document doc, Element parent,
String title, String author, int year) {
Element book = doc.createElement("book");
book.setAttribute("title", title);
book.setAttribute("author", author);
book.setAttribute("year", String.valueOf(year));
parent.appendChild(book);
}
}
Code Explanation
- DocumentBuilderFactory and DocumentBuilder create a DOM parser.
newDocument()creates an empty XML document. - createElement() and setAttribute() build the XML structure programmatically.
- Transformer converts the DOM tree into an XML file.
INDENT = "yes"produces nicely formatted output. - getElementsByTagName() finds elements by name. getAttribute() retrieves an attribute's value.
Everyday Example
An application configuration using XML:
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
public class ConfigXML {
public static void main(String[] args) throws Exception {
String xml = """
<config>
<database>
<host>localhost</host>
<port>3306</port>
<name>myapp</name>
</database>
<server>
<port>8080</port>
<maxThreads>100</maxThreads>
</server>
</config>
""";
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(
xml.getBytes()));
System.out.println("DB Host: " + getValue(doc, "host"));
System.out.println("DB Port: " + getValue(doc, "port"));
System.out.println("Server Port: " + doc
.getElementsByTagName("server").item(0)
.getChildNodes().item(1).getTextContent());
}
static String getValue(Document doc, String tag) {
return doc.getElementsByTagName(tag).item(0).getTextContent();
}
}
Summary
Java has a very complete XML ecosystem. DOM is a good fit for small documents, SAX/StAX for large documents. For modern development, consider JSON (Jackson/Gson) as a more compact alternative to XML — unless the XML format is mandated by an industry standard.