JAXB XML to Java Object Conversion | OnlineTutorialsPoint %

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAXB (Java Architecture for XML Binding) is a java framework that allows the developers to map java objects to XML. Here we are going to see how to convert an XML to Java Object.
JAXB provides two main features – that are marshalling and unmarshalling. Marshalling allows us to convert Java objects to XML whereas unmarshalling used to convert XML to Object.
In this example, let’s see how to unmarshal the XML.
Add the below jaxb-api dependency in pom.xml
<dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.3.1</version>
</dependency>
<!-- API, java.xml.bind module -->
       <dependency>
           <groupId>jakarta.xml.bind</groupId>
           <artifactId>jakarta.xml.bind-api</artifactId>
           <version>2.3.2</version>
       </dependency>

       <!-- Runtime, com.sun.xml.bind module -->
       <dependency>
           <groupId>org.glassfish.jaxb</groupId>
           <artifactId>jaxb-runtime</artifactId>
           <version>2.3.2</version>
       </dependency>
Now time to implement the logic to convert XML to Object.
Create a Java class that can be mapped with XML.
Book.java
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Book")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Book {
    private int id;
    private String name;
    private double price;

    // getters and setters
    // tostring
}

The above book class is the representation of the XML so that JAXB can map the XML fields to the book properties. The below program is to convert the XML string to Object.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;

public class XMLToObject {
    public static void main(String[] args){
        try {
            String xml = """
                    <Book>
                       <id>1</id>
                       <name>Java</name>
                       <price>200</price>
                    </Book>
                    """;
            Book book = getBookFromString(xml);
            System.out.println(book.toString());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    public static Book getBookFromString(String xml) throws JAXBException{
        JAXBContext jc = JAXBContext.newInstance(Book.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource streamSource = new StreamSource(new StringReader(xml));
        JAXBElement<Book> jaxbElement = unmarshaller.unmarshal(streamSource, Book.class);

        Book book = jaxbElement.getValue();
        return book;
    }
}
Output:
Book{id=1, name='Java', price=200.0}
We can even pass the XML file to JAXB context to convert the XML to object. In the below method instead of passing the XML string, parsing XML file as an input to the unmarshaller.
public static Book getBookFromFile() throws JAXBException{
    File file = new File("book.xml"); // XML file path
    JAXBContext jc = JAXBContext.newInstance(Book.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Book book = (Book)unmarshaller.unmarshal(file);
    return book;
}
Output:
Book{id=1, name='Java', price=200.0}
Java13 Text Blocks
JAXB Architecture
Happy Learning 🙂

JAXB Java Object to XML Conversion Example
JAXB Map to XML Conversion Example
Python String to int Conversion Example
Java String to int conversion Example
4 ways to create an Object in Java
Java – How to read CSV file and Map to Java Object
How to convert Java Object to JSON
How to convert JSON to Java Object Example
How to convert JSON to Java Map Object
Binary To Decimal Conversion Java Program
Binary To Hexadecimal Conversion Java Program
Decimal To Binary Conversion Java Program
Decimal To Hex Conversion Java Program
Decimal To Octal Conversion Java Program
Octal To Decimal Conversion Java Program

JAXB Java Object to XML Conversion Example
JAXB Map to XML Conversion Example
Python String to int Conversion Example
Java String to int conversion Example
4 ways to create an Object in Java
Java – How to read CSV file and Map to Java Object
How to convert Java Object to JSON
How to convert JSON to Java Object Example
How to convert JSON to Java Map Object
Binary To Decimal Conversion Java Program
Binary To Hexadecimal Conversion Java Program
Decimal To Binary Conversion Java Program
Decimal To Hex Conversion Java Program
Decimal To Octal Conversion Java Program
Octal To Decimal Conversion Java Program
 


Δ
 Install Java on Mac OS
 Install AWS CLI on Windows
 Install Minikube on Windows
 Install Docker Toolbox on Windows
 Install SOAPUI on Windows
 Install Gradle on Windows
 Install RabbitMQ on Windows
 Install PuTTY on windows
 Install Mysql on Windows
 Install Hibernate Tools in Eclipse
 Install Elasticsearch on Windows
 Install Maven on Windows
 Install Maven on Ubuntu
 Install Maven on Windows Command
 Add OJDBC jar to Maven Repository
 Install Ant on Windows
 Install RabbitMQ on Windows
 Install Apache Kafka on Ubuntu
 Install Apache Kafka on Windows
 Java8 – Install Windows
 Java8 – foreach
 Java8 – forEach with index
 Java8 – Stream Filter Objects
 Java8 – Comparator Userdefined
 Java8 – GroupingBy
 Java8 – SummingInt
 Java8 – walk ReadFiles
 Java8 – JAVA_HOME on Windows
 Howto – Install Java on Mac OS
 Howto – Convert Iterable to Stream
 Howto – Get common elements from two Lists
 Howto – Convert List to String
 Howto – Concatenate Arrays using Stream
 Howto – Remove duplicates from List
 Howto – Filter null values from Stream
 Howto – Convert List to Map
 Howto – Convert Stream to List
 Howto – Sort a Map
 Howto – Filter a Map
 Howto – Get Current UTC Time
 Howto – Verify an Array contains a specific value
 Howto – Convert ArrayList to Array
 Howto – Read File Line By Line
 Howto – Convert Date to LocalDate
 Howto – Merge Streams
 Howto – Resolve NullPointerException in toMap
 Howto -Get Stream count
 Howto – Get Min and Max values in a Stream
 Howto – Convert InputStream to String