Sunday, May 19, 2024
HomeJavaThe way to converts Java Object to XML

The way to converts Java Object to XML


JAXB, which stands for Java API for XML Binding or generally Java Structure for XML Binding is a decade-old know-how to instantly convert a Java object into an XML doc (marshaling) and again to XML file into Java object(unmarshalling). It makes use of a mixture of annotations and getters and setters to marshal Java objects into XML. JAXB truly defines the habits of an ordinary set of instruments and interfaces that routinely generate Java class recordsdata from an XML schema, keep in mind JAXB is definitely a framework and structure, not an implementation. The bundle java.xml.bind offers a runtime binding framework for shoppers to marshal, unmarshal and validate XML recordsdata in Java.

By the best way, JAXB just isn’t the one choice to parse XML in Java, you may at all times use SAX or DOM parser or JAXP API to transform XML to Java object and vice-versa. If you wish to be taught extra about XML processing in Java, I counsel to have a look at chapter 2 of Core Java Quantity 2 By Cay S. Horstmann. This guide covers not solely DOM and SAX but in addition StAX parser and finding info with XPath.

The way to use JAXB in Java – An Instance

Let’s have a look at how you should use JAXB to create an XML doc from Java courses That is how JAXB works, for instance you’ve gotten an Merchandise object that must be transformed to an XML doc, all it’s essential to do is create a category Merchandise with getters and annotate them appropriately as proven beneath :

@XmlRootElement
public class Merchandise{
    non-public int id;
    non-public String title;
    non-public lengthy value;
    
    public Merchandise(){
        // no argument constructor required by JAXB
    }
    public Merchandise(int id, String title, lengthy value) {
        tremendous();
        this.id = id;
        this.title = title;
        this.value = value;
    }

    @XmlElement
    public int getId() {
        return id;
    }

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

    @XmlElement
    public lengthy getPrice() {
        return value;
    }   
    
}

Then you definately create a marshaller from JAXBContext class and ask it to transform an occasion of sophistication Merchandise into XML, as proven beneath :

Merchandise dvd = new Merchandise(101, "Lord of the Rings", 10);
JAXBContext context = JAXBContext.newInstance(Merchandise.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(dvd, System.out);    

This may print the next XML String into your console :


You’ll be able to see how simple it’s to transform a Java object to XML utilizing JAXB. You needn’t fear about mapping sorts, opening tag, closing tag or doing something associated to XML by hand.

JAXB Example in Java

Right here is the entire Java program to transform a Java object to an XML file utilizing JAXB API :

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
* Java program to transform Java object to XML Doc utilizing
* JAXB API. Changing a Java object to XML can also be knonwn
* as marshalling and reverse course of is known as unmarshalling.
*
* @creator Javin Paul
*/
public class JAXBDemo{

    public static void major(String args[]) throws JAXBException {

        ultimate Merchandise dvd = new Merchandise(101, "Lord of the Rings", 10);
        ultimate JAXBContext context = JAXBContext.newInstance(Merchandise.class);
        ultimate Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(dvd, System.out);       
    }
    
}

@XmlRootElement
class Merchandise{
    non-public int id;
    non-public String title;
    non-public lengthy value;
    
    public Merchandise(){
        // no argument constructor required by JAXB
    }
    public Merchandise(int id, String title, lengthy value) {
        tremendous();
        this.id = id;
        this.title = title;
        this.value = value;
    }

    @XmlElement
    public int getId() {
        return id;
    }

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

    @XmlElement
    public lengthy getPrice() {
        return value;
    }
    
    
}

Issues to remember :

1) Your Java class will need to have a no-argument constructor, in any other case, JAXB is not going to in a position to marshal it. You’re going to get the next Exception :

Exception in thread "major" 
com.solar.xml.inside.bind.v2.runtime.IllegalAnnotationsException:
 1 counts of IllegalAnnotationExceptions
Merchandise does not have a no-arg default constructor.
    at com.solar.xml.inside.bind.v2.runtime
.IllegalAnnotationsException$Builder.examine(Unknown Supply)
    at com.solar.xml.inside.bind.v2.runtime
.JAXBContextImpl.getTypeInfoSet(Unknown Supply)
    at com.solar.xml.inside.bind.v2.runtime
.JAXBContextImpl.<init>(Unknown Supply)
    at com.solar.xml.inside.bind.v2.runtime
.JAXBContextImpl.<init>(Unknown Supply)
    at com.solar.xml.inside.bind.v2.runtime.
JAXBContextImpl$JAXBContextBuilder.construct(Unknown Supply)
    at com.solar.xml.inside.bind.v2.ContextFactory.
createContext(Unknown Supply)
    at solar.mirror.NativeMethodAccessorImpl.invoke0(Native Methodology)
    at solar.mirror.NativeMethodAccessorImpl.invoke(Unknown Supply)
    at solar.mirror.DelegatingMethodAccessorImpl.invoke(Unknown Supply)
    at java.lang.mirror.Methodology.invoke(Unknown Supply)
    at javax.xml.bind.ContextFinder.newInstance(Unknown Supply)
    at javax.xml.bind.ContextFinder.newInstance(Unknown Supply)
    at javax.xml.bind.ContextFinder.discover(Unknown Supply)
    at javax.xml.bind.JAXBContext.newInstance(Unknown Supply)
    at javax.xml.bind.JAXBContext.newInstance(Unknown Supply)

2) At all times keep in mind to annotate your Java class with @XmlRootElement annotation, this could be your major tag in XML and every property utilizing @XmlElement, they’ll seem as baby aspect of the primary tag.

That is all about learn how to convert Java Object to XML. In subsequent tutorial you’ll discover ways to do unmarshalling i.e. changing an XML again to Java object. Despite the fact that you may learn about numerous XML parsers e.g. DOM, SAX and StAX, its good to know JAXP and JAXB as properly. As Java and XML go hand and hand, they add one other device into the Java developer’s arsenal.

If you’re in search of some books to be taught XML processing in Java, you may at all times refer core Java quantity 2 for primary data. It offers you good overview of various parser, XML binding and XPath, however if you wish to be taught extra in-depth then you may refer Java and XML by Brett McLaughlin. It is one other good guide to find out about XML processing in Java.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments