Tuesday, November 3, 2026

Java XML Parsers – Complete Guide

Java XML Parsers – Complete Guide

1. Introduction to XML Parsing in Java

XML (Extensible Markup Language) is used to store, transport, and exchange structured data between applications.

Java provides several APIs to read, write, parse, and manipulate XML documents.

XML parsing is the process of reading an XML document and extracting its elements, attributes, and values.

Java XML Parsers – Complete Guide


Example XML

<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee id="101">
        <name>Sumit</name>
        <age>32</age>
        <salary>50000</salary>
    </employee>
    <employee id="102">
        <name>Amit</name>
        <age>30</age>
        <salary>60000</salary>
    </employee>
</employees>

2. Types of XML Parsers in Java

Java supports several XML parsing approaches.

XML ParserDescription
DOM Parser     Loads the entire XML document into memory as a tree.
SAX Parser     Reads XML sequentially using events.
StAX Parser    Reads XML using a pull-based event mechanism.
JAXB    Converts XML into Java objects and vice versa.
XPath    Extracts specific information from XML using expressions.

3. DOM Parser in Java

DOM (Document Object Model) parses the complete XML document and represents it as a tree structure.

Features

  • Loads the entire XML document into memory.
  • Allows random access to XML elements.
  • Supports reading, updating, adding, and deleting nodes.
  • Suitable for small and medium-sized XML files.

Example: Read XML Using DOM Parser

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.File;

public class DOMParserExample {

    public static void main(String[] args) throws Exception {

        File file = new File("employees.xml");

        DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();

        Document document = builder.parse(file);

        document.getDocumentElement().normalize();

        NodeList list = document.getElementsByTagName("employee");

        for (int i = 0; i < list.getLength(); i++) {

            Element element = (Element) list.item(i);

            String id = element.getAttribute("id");

            String name = element.getElementsByTagName("name")
                    .item(0).getTextContent();

            String age = element.getElementsByTagName("age")
                    .item(0).getTextContent();

            String salary = element.getElementsByTagName("salary")
                    .item(0).getTextContent();

            System.out.println("ID: " + id);
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Salary: " + salary);
        }
    }
}

Output

ID: 101
Name: Sumit
Age: 32
Salary: 50000

ID: 102
Name: Amit
Age: 30
Salary: 60000

4. SAX Parser in Java

SAX (Simple API for XML) is an event-based XML parser. It reads XML sequentially and triggers events when it encounters XML elements, attributes, and text.

Features

  • Reads XML sequentially.
  • Does not load the entire document into memory.
  • Suitable for large XML files.
  • Does not support random access to XML elements.

Example: Read XML Using SAX Parser

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import java.io.File;

public class SAXParserExample {

    public static void main(String[] args) throws Exception {

        SAXParserFactory factory = SAXParserFactory.newInstance();

        SAXParser parser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {

            public void startElement(
                    String uri,
                    String localName,
                    String qName,
                    Attributes attributes) {

                System.out.println("Start Element: " + qName);
            }

            public void characters(char[] ch, int start, int length) {

                String value = new String(ch, start, length).trim();

                if (!value.isEmpty()) {
                    System.out.println("Value: " + value);
                }
            }

            public void endElement(
                    String uri,
                    String localName,
                    String qName) {

                System.out.println("End Element: " + qName);
            }
        };

        parser.parse(new File("employees.xml"), handler);
    }
}

5. StAX Parser in Java

StAX (Streaming API for XML) is a pull-based XML parser.

Unlike SAX, where the parser pushes events to your application, StAX allows your application to request the next XML event.

Features

  • Reads XML sequentially.
  • Memory efficient.
  • Provides more control over parsing.
  • Suitable for large XML files.

Example: Read XML Using StAX Parser

import javax.xml.stream.*;
import java.io.FileInputStream;

public class StAXParserExample {

    public static void main(String[] args) throws Exception {

        XMLInputFactory factory = XMLInputFactory.newInstance();

        XMLStreamReader reader = factory.createXMLStreamReader(
                new FileInputStream("employees.xml"));

        while (reader.hasNext()) {

            int event = reader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {

                System.out.println("Start Element: "
                        + reader.getLocalName());
            }

            if (event == XMLStreamConstants.CHARACTERS) {

                String value = reader.getText().trim();

                if (!value.isEmpty()) {
                    System.out.println("Value: " + value);
                }
            }
        }

        reader.close();
    }
}

6. JAXB – Java Architecture for XML Binding

JAXB is used to convert XML data into Java objects and Java objects into XML.

  • Marshalling: Java Object to XML.
  • Unmarshalling: XML to Java Object.

Example: JAXB Employee Class

import jakarta.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {

    private int id;
    private String name;
    private int age;

    public Employee() {
    }
}

Example: JAXB Unmarshalling

import jakarta.xml.bind.*;
import java.io.File;

public class JAXBExample {

    public static void main(String[] args) throws Exception {

        JAXBContext context =
                JAXBContext.newInstance(Employee.class);

        Unmarshaller unmarshaller = context.createUnmarshaller();

        Employee employee = (Employee)
                unmarshaller.unmarshal(new File("employee.xml"));

        System.out.println("XML converted into Java Object");
    }
}

Note: JAXB is not bundled with modern JDK versions. Add the JAXB API and runtime dependencies to your Maven project.

7. XPath in Java

XPath (XML Path Language) is used to navigate and select specific elements or attributes from XML documents.

Features

  • Extract specific XML elements.
  • Select elements based on conditions.
  • Navigate nested XML structures.
  • Useful for XML test automation and data validation.

Example: XPath in Java

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import java.io.File;

public class XPathExample {

    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();

        Document document = builder.parse(new File("employees.xml"));

        XPath xpath = XPathFactory.newInstance().newXPath();

        String expression = "//employee[name='Sumit']/salary";

        String salary = xpath.evaluate(expression, document);

        System.out.println("Salary: " + salary);
    }
}

Output

Salary: 50000


Conclusion

Java provides multiple XML parsing techniques, including DOM, SAX, StAX, JAXB, and XPath. Each parser has different capabilities and use cases.

For Java developers and automation testers, start with DOM parsing, followed by XPath, SAX, StAX, and JAXB. XPath is particularly useful when validating XML responses in API automation testing.

Frequently Asked Questions (FAQ)

1. What are the different XML parsers available in Java?

The main XML parsing technologies in Java are DOM, SAX, StAX, JAXB, and XPath.

2. Which XML parser is best for large XML files?

SAX and StAX are suitable for large XML files because they process data incrementally instead of loading the entire document into memory.

3. What is the difference between DOM and SAX parsers?

DOM loads the complete XML document into a tree structure, whereas SAX processes XML sequentially using parser-generated events.

4. What is JAXB used for in Java?

JAXB converts XML data into Java objects through unmarshalling and converts Java objects into XML through marshalling.

5. What is XPath in Java?

XPath is used to locate and extract specific elements, attributes, and values from XML documents using expressions.

6. Is JAXB included in modern Java versions?

No. JAXB was removed from the JDK starting with Java 11 and must be added separately using Maven dependencies or another dependency management tool.

7. What is XML parsing in automation testing?

XML parsing in automation testing is used to extract values, validate XML responses, verify attributes, and compare expected and actual XML data.

8. What is an XXE vulnerability?

XXE (XML External Entity) is a security vulnerability that can occur when an XML parser processes untrusted external entity references. Secure parser configuration helps prevent this vulnerability.

No comments:

Post a Comment