The Wayback Machine - https://web.archive.org/web/20241118220558/https://www.geeksforgeeks.org/java-architecture-for-xml-binding-jaxb-set-1/
Open In App

Java Architecture for XML Binding ( JAXB ) | Set-1

Last Updated : 02 Aug, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Java Architecture for XML Binding (JAXB) defines an API for reading and writing Java objects to and from XML documents. JAXB gives Java developers an efficient and standard way of mapping between XML and Java code. JAXB makes it easier for developers to extend their applications with XML and Web Services technologies.At First JAXB was developed as a separate project but it was finally became part of JDK in Java 6.

Java Architecture for XML Binding Functions

Application of JAXB

JAXB framework is helpful to perform the following operations:

  • Change XML content into a Java representation.
  • Access and update the Java representation
  • Change the Java representation into XML content.

JAXB Annotations

JAXB uses annotations to indicate the central elements. Some Basics JAXB Annotations which can be used in your java class for JAXB operations are:

Annotation Description
@XmlRootElement Must require annotation for the Object to be used in JAXB. It defines the root element for the XML content.
@XmlType It maps the class to the XML schema type. This is optional. We use @XmlType (propOrder = {“list of attributes in order”}) annotation to define Specific order of elements in XML file.
@XmlTransient To exclude a object from being mapped as part of the inheritance hierarchy you simply need to annotate it with @XmlTransient.
@XmlAttribute This will create the Object property as attribute.
@XmlElement It is used to define element in XML file.You can use @XmlElement(name = “Age”) if you want to give a specific name to that element.

Two Basic Concept related to JAXB are :

  1. Marshalling : Convert a java Object to xml
  2. UnMarshalling : Convert xml to java object

Marshalling

Below is the step by step algorithm for converting Java Objects to XML(Marshalling):

  1. First Create Java Objects to be Marshalled.
  2. Create JAXBContext Object and initializing Marshaller Object.
  3. To get the formatted xml output one can set JAXB_FORMATTTED_OUTPUT to True(this Step is optional).
  4. Create xml file object by providing location of file as parameter to File Class
  5. Call marshal method on Marshaller Object and pass created XML File object to marshal method.
  6. Now the XMl file is created.

Example: First let’s Create a Student object with FullName, StudentDegree, StudentMarks attributes then we are going to convert this object to XML Schema by following above steps.

Creating Student.java class with FullName, StudentDegree, StudentMarks attributes.




import java.util.ArrayList;
  
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
  
// Below annotation defines root element of XML file
@XmlRootElement
public class Student {
  
    private String FullName;
    private String StudentDegree;
    private String StudentMarks;
    public String getFullName()
    {
        return FullName;
    }
    // Sets element of xml with element name is "Student Name"
    @XmlElement(name = "Student Name")
    public void setFullName(String fullName)
    {
        FullName = fullName;
    }
    public String getStudentDegree()
    {
        return StudentDegree;
    }
    @XmlElement(name = "Student Degree")
    public void setStudentDegree(String studentDegree)
    {
        StudentDegree = studentDegree;
    }
    public String getStudentMarks()
    {
        return StudentMarks;
    }
    @XmlElement(name = "Student Marks")
    public void setStudentMarks(String studentMarks)
    {
        StudentMarks = studentMarks;
    }
}


Main Class : JAVAObjToXml.java which is going to convert Student object to XML Schema.




import java.io.File;
import java.util.ArrayList;
  
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
  
public class JAVAObjToXml {
    public static void main(String[] args)
    {
  
        // creating Student object
        Student student = new Student();
        student.setFullName("Aman Singh");
        student.setStudentDegree("Degree");
        student.setStudentMarks("688/900");
  
        try {
  
            // Create JAXB context and initializing Marshaller
            JAXBContext context = JAXBContext.newInstance(Student.class);
            Marshaller marshaller = context.createMarshaller();
  
            // For formatted output of xml
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  
            // Create xml file object
            File XMLfile = new File("D:\\StudentRecord.xml");
  
            // Java object to XML file
            marshaller.marshal(student, XMLfile);
            // Print to console
            marshaller.marshal(student, System.out);
        }
        catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}


Output:

generated StudentRecord.xml File for Student Object.




<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
    <Student Name>Aman Singh</Student Name>
    <Student Degree>Degree</Student Degree>
    <Student Marks>688/900</Student Marks>
</student>


Pros and Cons of Using JAXB

Pros:

  • Easy to marshal XML file to other data targets like inputStream, DOM node.
  • Easy to unmarshal XML file from other data targets.
  • No need to be aware of XML parsing techniques.
  • simple to use than DOM or SAX parser

Cons:

  • JAXB is high layer API so it has less control on parsing than SAX or DOM.
  • It is slower than SAX.

References:



Similar Reads

Spring and JAXB Integration
The term JAXB stands for Java Architecture for XML Binding. Java programmers may use it to translate Java classes to XML representations. Java objects may be marshaled into XML and vice versa using JAXB. Sun provides an OXM (Object XML Mapping) or O/M framework. Note: The biggest and only advantage of JAXB is as there's no need to develop callback
5 min read
Overview of Data Binding in Android Architecture Components
This article describes the idea behind the Data Binding and MVVM design pattern and its components. If you would like to experiment with it hands-on, open an old project with spaghetti code. If you don’t have one, you'll get one from GitHub. Then, attempt to use the MVVM components introduced during this article. In some ways, software development
4 min read
Difference between Early and Late Binding in Java
Early Binding: The binding which can be resolved at compile time by the compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time. Example: Java Code public class NewClass { public static class superclass { static void print() { System.out.println(&quot;print in superclass.&qu
2 min read
Differences between Dynamic Binding and Message Passing in Java
Dynamic Binding: In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method. Dynamic binding is also called Late binding. Message Passing: Message Passing in terms of computers is communication between processes. It is a for
3 min read
Static vs Dynamic Binding in Java
There are certain key points that are needed to be remembered before adhering forward where we will be discussing and implementing static and dynamic bindings in Java later concluding out the differences. private, final and static members (methods and variables) use static binding while for virtual methods (In Java methods are virtual by default) b
5 min read
How to Implement View Binding Inside Dialog in Android?
In android, View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout. What we
4 min read
Data Binding in Spring MVC with Example
Data Binding, as the name itself, is a self-explanatory word. In data binding what we have to do is we have to capture or store the data so that we can bind that data with another resource (for example displaying the data in the frontend part) as per our needs or we can also read the data from a variable and display it as per our requirements. For
8 min read
Two-Way Data Binding in Spring MVC with Example
Data Binding, as the name itself, is a self-explanatory word. In data binding what we have to do is we have to capture or store the data so that we can bind that data with another resource (for example displaying the data in the frontend part) as per our needs or we can also read the data from a variable and display it as per our requirements. For
7 min read
How Jackson Data Binding Works in Spring Boot?
Spring is a framework of java that is used to build high-level, large-scale enterprise applications. And the most common thing we do in almost every application is transfer data between the front-end and back-end (to the server). Supposedly, when we perform Update, Create, or any other operation that impacts changes in the Database then what happen
4 min read
javax.xml.crypto Package in Java
Common classes having the XML cryptography for the Package javax.xml.crypto. now this crypto package includes similar classes that are used to accessing XML cryptographic on its operations, such as creating an XML signature or encrypted XML data. There are two types of javax.xml.crypto classes in this package that are KeySelector class, which allow
4 min read
How to Create and Modify Properties File Form Java Program in Text and XML Format?
Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article
5 min read
XML EventWriter in Java StAX API
Java StAX API was introduced in Java 6 and considered superior to DOM and SAX parsers. We can use Java StAX parser to read XML file and java Streaming API for XML (Java StAX) provides implementation for processing XML in java. The XMLEventWriter class in the Java StAX API allows you to write StAX XMLEvent's either to a Writer, an OutputStream, or a
3 min read
XML Output Factory in Java StAX
StAX provides various classes to create XML stream readers, writers, and events by using the XMLInputFactory, XMLOutputFactory, and XMLEventFactory classes. In this article we're going to study about XML Output Factory . The class javax.xml.stream.XMLOutputFactory is a root component of the Java StAX API. From this class you can create both an XMLS
3 min read
XML EventWriter in Java StAX
Java StAX API is also called Java Streaming API for XML and it was introduced in Java 6. This is the most wanted API while considering DOM and SAX parsers. StAX consists of cursor-based API and iterator-based API. In this article, let us see how to prepare an XML file in java using StAX Iterator-based API (XMLEventWriter). For creating an XML struc
5 min read
StAX XML Parser in Java
This article focuses on how one can parse a XML file in Java.XML : XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. That’s why, the design goals of XML emphasize simplicity, generality, and usability across the Internet. Why StAX instead of SAX ? SAX: The
6 min read
Java XML Parsers
XML is a versatile data format that is to be used for storing and transporting structured information. A significant amount of configuration files, data interchange, and others are done using XML in Java. For effective manipulation of XML documents in Java, there exists a set of parsers for XML. These parsers are capable of reading XML content and
7 min read
How to Resolve WEB xml is missing and failOnMissingWebXml is set to true in Eclipse/STS?
Eclipse/STS IDE is generally used to develop Spring applications and what happens is whenever we are creating a simple Maven project and if the web.xml is missing or you have deleted that file then you may encounter this problem inside the pom.xml file corresponding to which do refer to the below image as follows: Now we are going to discuss how ca
2 min read
Hibernate Mapping Set using XML
In Hibernate, if we want to map one table to another with the help of a set then we use Set mapping. Set mapping can be performed if the model class or persistent class contains a set as its element. To perform set mapping, we can use a set in the mapping file. let's see how we can configure the XML mapping file for the mapping set in hibernate. Pr
5 min read
Web technologies | HTML and XML | Question 1
Which of the following is an advantage of putting presentation information in a separate CSS file rather than in HTML itself? (A) The content becomes easy to manage (B) Becomes easy to make site for different devices like mobile by making separate CSS files (C) CSS Files are generally cached and therefore decrease server load and network traffic. (
1 min read
Displaying XML Using XSLT
XSLT stands for Extensible Stylesheet Language Transformation. XSLT is used to transform XML document from one form to another form. XSLT uses Xpath to perform matching of nodes to perform these transformation . The result of applying XSLT to XML document could be an another XML document, HTML, text or any another document from technology perspecti
3 min read
XML | Syntax
Prerequisite: XML | Basics In this article, we are going to discuss XML syntax rule which is used while writing an XML document or an XML application. It is a very simple and straight forward to learn and code. Below is a complete XML document to discuss each component in detail. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
3 min read
XML | Tags
XML tags are the important features of XML document. It is similar to HTML but XML is more flexible then HTML. It allows to create new tags (user defined tags). The first element of XML document is called root element. The simple XML document contain opening tag and closing tag. The XML tags are case sensitive i.e. <root> and <Root> bot
2 min read
XML | Elements
The XML elements are the basic building block of the XML document. It is used as a container to store text elements, attributes, media objects etc. Every XML documents contain at least one element whose scopes are delimited by start and end tags or in case of empty elements it is delimited by an empty tag. Syntax: <element-name attributes> Co
2 min read
How to draw Horizontal and Vertical lines in an Android App using XML
This article demonstrates how to draw a horizontal and a vertical line in an Android app. Although we have countless XML tags to meet almost all of our needs, unfortunately, we don't have any tag such as <line> tag to draw the line. However, <view> tag can be used in XML as a workaround. NOTE: The "view" tag is different than the View c
2 min read
Spring - AOP AspectJ Xml Configuration
Spring allows you to specify aspects, recommendations, and pointcuts in an XML file. Annotations were used in the aop examples on the preceding page. The XML configuration file will now show us the same samples. Let's look at the XML components that describe advice. aop:before: It's used before the real business logic procedure is called.aop:after:
7 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
How to check the structure of an XML Document ?
Introduction : XML document is a well-organized collection of components and associated markup. An XML document can hold a wide range of information. For instance, a database having numbers or a mathematical equation etc. Example: A simple document can be created as - <?xml version = "1.0"?> <Student-info> <name>Tanya Bajaj</na
3 min read
Which tag is used to find the version of XML and syntax ?
Extensible Markup Language (XML) is a markup language, defining a ruleset for encoding documents in both formats that is human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. XML is designed to be self-descriptive along with storing and transporting the data. It is a textual
2 min read
Servlet - welcome-file-list in web.xml
The web.xml file's welcome-file-list property is used to establish a list of welcome files. If you don't supply a file name while loading the project in the browser, the tag <welcome-file-list> is used to define the files that will be called by the server by default. The server looks for the welcome file in the following sequence by default:
2 min read
Spring - REST XML Response
The popularity of REST API is increasing day by day as it fulfills architecting an application in a convenient manner. A REST API is an acronym for 'Representational state transfer'. It is also called RESTful web services. It is also a 'Controller', but with a difference that Rest Controller returns Data, while Controller returns a View of 'Model-V
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg