Core Java

JAXP vs JAXB – Comparing XML Processing APIs in Java

This article explores the differences between Java JAXP vs JAXB, including their features, use cases, and how they contribute to XML processing in Java applications.

1. Introduction

Regarding XML processing in Java applications, Java provides a rich ecosystem of libraries and APIs for working with XML data. JAXP (Java API for XML processing) and JAXB (Java Architecture for XML Binding) are two popular options. These APIs provide essential functionalities for parsing, manipulating, and binding XML data in Java. This article explores the differences between JAXP and JAXB, use cases, and how they contribute to XML processing in Java applications.

2. JAXP (Java API for XML Processing)

JAXP, which stands for Java API for XML processing, provides Java developers with a standardized way to process, parse, and manipulate XML documents in their applications. JAXP is part of Java Standard Edition (Java SE) and offers a set of interfaces and classes that enable developers to work with XML documents using different parsing models and processing techniques.

2.1 JAXP Components

JAXP contains the following parsing interfaces

  • SAX (Simple API for XML) Parsing Interface: SAX is an event-driven XML parsing model provided by JAXP. It operates by sequentially reading an XML document and notifying the application of specific events as it encounters elements, attributes, text, and other components.
  • DOM (Document Object Model) Parsing Interface: DOM is a tree-based XML parsing model offered by JAXP. It creates an in-memory representation of the entire XML document as a tree of objects, allowing developers to navigate, modify, and manipulate the document’s structure and content.
  • StAX (Streaming API for XML) Parsing Interface: StAX provides a pull-parsing XML processing model in JAXP. Developers use StAX to pull events from the XML document, giving them control over the parsing process.
  • XSLT (XML Stylesheet Language Transformations): JAXP supports XSLT transformations, allowing developers to apply XSL stylesheets to XML documents for various purposes such as data transformation or rendering.

2.2 Use Cases of JAXP

JAXP offers tools to handle various XML-related tasks in Java applications. The following list provides some use cases of JAXP

  • Parsing and Reading XML: JAXP allows developers to extract and use data from XML documents in their applications.
  • Data Transformation: Using XSLT, JAXP enables developers to convert XML data from one format to another.
  • Generating XML: Developers can use JAXP to create XML documents programmatically.
  • Web Services: JAXP plays a role in parsing and processing XML data in web services, allowing data exchange between different applications over the internet.

2.3 Example of How To Parse an XML Document using JAXP

Below is an example of how to parse an XML document using JAXP’s DOM (Document Object Model) parsing model in Java. First, Let’s create a Java Maven project named JAXPDOMParserExample.java and add an XML document to the project named authors.xml with the following content:

<library>
    <book>
        <title>Gulliver's Travels</title>
        <author>Jonathan Swift</author>
    </book>
<book>
        <title>Oliver Twist</title>
        <author>Charles Dickens</author>
    </book>
    <book>
        <title>Things Fall Apart</title>
        <author>Chinua Achebe</author>
    </book>
    <book>
        <title>A Midsummer Night's Dream</title>
        <author>William Shakespeare</author>
    </book>
</library>

Next, update the main method of the class to parse XML document named authors.xml using JAXP’s DOM parser. The updated class content should be like this

public class JAXPDOMParserExample {

    public static void main(String[] args) {
         try {
            // Create a DocumentBuilderFactory instance
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // Create a DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML document
            Document document = builder.parse(new File("authors.xml"));

            // Get the root element
            Element root = document.getDocumentElement();

            // Get a list of all Author's elements
            NodeList authorList = root.getElementsByTagName("book");

            // Loop through the book elements
            for (int i = 0; i < authorList.getLength(); i++) {
                Element authors = (Element) authorList.item(i);
                String title = authors.getElementsByTagName("title").item(0).getTextContent();
                String author = authors.getElementsByTagName("author").item(0).getTextContent();
                System.out.print("Title: " + title );
                System.out.println(", Author: " + author);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a DocumentBuilderFactory instance and use it to create a DocumentBuilder. We parse the XML document using the parse method and obtain a Document object. We get the root element of the document using getDocumentElement. We retrieve a list of all elements using getElementsByTagName. We loop through the book elements, extract the title and author using getElementsByTagName, and print the information.

The output from running the program is shown below

Fig 1.0 Output from running JAXPDOMParserExample.java
Fig 1.0 Output from running JAXPDOMParserExample.java

3. JAXB (Java Architecture for XML Binding)

JAXB, which stands for Java Architecture for XML Binding, is a Java technology that allows developers to convert Java objects into XML representation and vice versa. It provides a convenient way to map XML documents to Java classes and objects, enabling seamless integration of XML data into Java applications.

3.1 Key Concepts of JAXB

JAXB has the following key concepts:

  • Marshaling: The process of converting Java objects into XML representation. JAXB takes Java objects and generates corresponding XML documents based on predefined mappings.
  • Unmarshalling: The process of converting XML data into Java objects. JAXB reads XML documents and creates corresponding Java objects, populating them with data from the XML.
  • Annotations: JAXB uses annotations to define the mapping between Java classes and XML elements, attributes, and structures.
  • Object-XML Binding: JAXB establishes a binding between Java classes and XML structures, ensuring that data can be seamlessly transferred between the two formats.

3.2 Use Cases of JAXB

JAXB offers various benefits which include eliminating the need for manual XML parsing and serialization, making it simpler to integrate XML data into Java applications. By defining mappings between XML and Java, JAXB ensures that the structure of the data remains consistent during conversion. The list below shows some use cases of JAXB

  • Web Services Integration: JAXB is commonly used in web services to convert XML-based requests and responses into Java objects that can be processed by the application.
  • XML Data Storage: JAXB is useful for persisting and retrieving Java objects in XML-based data stores or databases.
  • Data Transformation: JAXB can be used to convert data between different systems, formats, or versions by providing mappings that accommodate the differences.
  • Configuration Files: JAXB can be employed to read and write configuration files or settings in XML format, making it easier to manage and modify application settings.

3.3 Example of How to Perform XML Processing using JAXB

JAXB annotations make code more readable and maintainable, as developers can define mappings directly within the Java classes. Below is an example of how to perform XML processing using JAXB.

Note that prior to Java 11, JAXB was a part of the JVM that could be used directly without the addition of external libraries. With Java 11, JAXB is no longer part of the JRE therefore developers need to configure the JAXB library in your pom.xml file in a Maven project as shown below.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jcg</groupId>
    <artifactId>JAXBExample</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <exec.mainClass>com.jcg.jaxbexample.JAXBExample</exec.mainClass>
    </properties>
    
    <dependencies>

<!-- JAXB API only -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
            <type>jar</type>
        </dependency>

<!-- JAXB Implementation -->
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.3.4</version>
        </dependency>

    </dependencies>
</project>

Next, create a Java application named JAXBExample.java to be used as our main class in our application, and then create Authors.java a class that represents information about some authors and their books in the project as shown below:

@XmlRootElement
public class Authors {
    private String title;
    private String author;

    public Authors() {
    }

    public Authors(String title, String author) {
        this.title = title;
        this.author = author;
    }

    @XmlElement
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @XmlElement
    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}

Next, update the JAXBExample.java class to demonstrate marshalling (Java to XML) and unmarshalling (XML to Java) using JAXB. The content of the updated class should look like this:

public class JAXBExample {

    public static void main(String[] args) throws JAXBException {
        // Create Authors object
        Authors authors = new Authors("Gullivers Travels", "Jonathan Swift");

        // Marshalling: Convert Java object to XML
        JAXBContext context = JAXBContext.newInstance(Authors.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(authors, writer);
        String xmlString = writer.toString();
        System.out.println("Marshalled XML:");
        System.out.println(xmlString);

        // Unmarshalling: Convert XML to Java object
        String xmlInput = "\n" +
                "Oliver TwistCharles Dickens";
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Authors unmarshalledBook = (Authors) unmarshaller.unmarshal(new StringReader(xmlInput));

        System.out.println("\nUnmarshalled Authors:");
        System.out.println("Title: " + unmarshalledBook.getTitle());
        System.out.println("Author: " + unmarshalledBook.getAuthor());
    }
}

In this example, we created an Authors object and populate it with data. We use JAXBContext to convert the Authors object into a XML string. We provide an XML input string and use JAXBContext to create an unmarshaller. We then convert the XML string back into an Authors object. When we run the program, it should output the screenshot shown below.

Fig 2. Output from running JAXBExample.java
Fig 2. Output from running JAXBExample.java

4. JAXP and JAXB Comparison

Below is a tabular comparison between JAXP and JAXB based on various aspects

ASPECTJAXPJAXB
AnnotationsNo specific annotations@XmlRootElement, @XmlElement, @XmlType
Main ComponentsSAX, DOM, StAXMarshalling, Unmarshalling
API ApproachRead, modify, or validate XML sequentially using events or tree structureConvert Java objects to/from XML representation
Development ComplexityMore coding effort, manual handling of XML events or nodesLess coding, automated XML mapping
Use CasesParsing, transforming, and validating XMLIntegrating XML data into Java applications
Integration with Java ObjectsLimitedSeamless integration using annotations
Table 1 – Summary of JAXP and JAXB comparison

5. Opting For JAXP or JAXB Based on Requirements

JAXP and JAXB serve different purposes, and their choice depends on the specific requirements of your project. JAXP is used for XML processing, parsing, and manipulation, whereas JAXB is used for conversion between Java objects and XML representations. Depending on your application’s needs, you might choose one or both of these APIs to achieve your goals.

6. Conclusion

In this article, we have discussed JAXP and JAXB and looked at some of their use cases, features, key components, and examples.

In conclusion, JAXP and JAXB are two essential components used for Java’s XML processing with each catering to distinct needs. JAXP serves as a toolkit for XML processing that enables developers to efficiently parse, transform, and validate XML documents. By using annotations like @XmlRootElement and @XmlElement, JAXB simplifies the conversion process between Java objects and XML.

7. Download the Source Code

This was an example of JAXP vs JAXB – Comparing XML Processing APIs in Java.

Download
You can download the full source code of this example here: JAXP vs JAXB – Comparing XML Processing APIs in Java

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button