XML with Java
Java has comprehensive built-in XML support through the javax.xml package. It supports DOM, SAX, StAX, XSLT transformation, and XML Schema validation — all without external libraries. For advanced needs, third-party libraries like JDOM2 and dom4j offer simpler APIs.
Parsing XML with DOM
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
public class XMLReader {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("products.xml"));
doc.getDocumentElement().normalize();
NodeList products = doc.getElementsByTagName("product");
for (int i = 0; i < products.getLength(); i++) {
Element p = (Element) products.item(i);
String id = p.getAttribute("id");
String name = p.getElementsByTagName("name")
.item(0).getTextContent();
String price = p.getElementsByTagName("price")
.item(0).getTextContent();
System.out.println(id + ": " + name + " — INR " + price);
}
}
}
Building XML with Java DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("catalog");
doc.appendChild(root);
Element product = doc.createElement("product");
product.setAttribute("id", "P001");
Element name = doc.createElement("name");
name.setTextContent("USB Hub");
product.appendChild(name);
root.appendChild(product);
// Write to file
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult("output.xml"));
Parsing XML with StAX (Pull Parsing)
import javax.xml.stream.*;
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(
new FileInputStream("products.xml"));
while (reader.hasNext()) {
int event = reader.next();
if (event == XMLStreamConstants.START_ELEMENT) {
System.out.println("Start: " + reader.getLocalName());
} else if (event == XMLStreamConstants.CHARACTERS) {
String text = reader.getText().trim();
if (!text.isEmpty()) System.out.println("Text: " + text);
}
}
reader.close();
Key Points to Remember
- Java's DocumentBuilder parses XML into a DOM Document object.
- getTextContent() returns the combined text of an element including all descendants.
- Transformer serializes a DOM Document to a file or stream.
- StAX (XMLStreamReader) is Java's pull-parsing model — lower memory than DOM.
- Always call doc.getDocumentElement().normalize() after parsing to clean up whitespace text nodes.
