Java create xml from object

How to converts Java Object to XML — JAXB Example

JAXB, which stands for Java API for XML Binding or sometimes Java Architecture for XML Binding is a decade-old technology to directly convert a Java object into an XML document (marshaling) and back to XML file into Java object(unmarshalling). It uses a combination of annotations and getters and setters to marshal Java objects into XML. JAXB actually defines the behavior of a standard set of tools and interfaces that automatically generate Java class files from an XML schema, remember JAXB is actually a framework and architecture, not an implementation. The package java.xml.bind provides a runtime binding framework for clients to marshal, unmarshal and validate XML files in Java.

By the way, JAXB is not the only option to parse XML in Java, you can always use SAX or DOM parser or JAXP API to convert XML to Java object and vice-versa. If you want to learn more about XML processing in Java, I suggest to look at chapter 2 of Core Java Volume 2 By Cay S. Horstmann. This book covers not only DOM and SAX but also StAX parser and locating information with XPath.

How to use JAXB in Java — An Example

Let’s see how you can use JAXB to create an XML document from Java classes This is how JAXB works, let’s say you have an Item object that needs to be converted to an XML document, all you need to do is create a class Item with getters and annotate them appropriately as shown below :

@XmlRootElement public class Item< private int id; private String name; private long price; public Item()< // no argument constructor required by JAXB > public Item(int id, String name, long price) < super(); this.id = id; this.name = name; this.price = price; > @XmlElement public int getId() < return id; > @XmlElement public String getName() < return name; > @XmlElement public long getPrice() < return price; > >

Then you create a marshaller from JAXBContext class and ask it to convert an instance of class Item into XML, as shown below :

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

How to use JAXB in Java with Example

You can see how easy it is to convert a Java object to XML using JAXB. You don’t need to worry about mapping types, opening tag, closing tag or doing anything related to XML by hand.

Читайте также:  Css column min heights

JAXB Example in Java

Here is the complete Java program to convert a Java object to an XML file using 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 convert Java object to XML Document using * JAXB API. Converting a Java object to XML is also knonwn * as marshalling and reverse process is called unmarshalling. * * @author Javin Paul */ public class JAXBDemo< public static void main(String args[]) throws JAXBException < final Item dvd = new Item(101, "Lord of the Rings", 10); final JAXBContext context = JAXBContext.newInstance(Item.class); final Marshaller marshaller = context.createMarshaller(); marshaller.marshal(dvd, System.out); > > @XmlRootElement class Item< private int id; private String name; private long price; public Item()< // no argument constructor required by JAXB > public Item(int id, String name, long price) < super(); this.id = id; this.name = name; this.price = price; > @XmlElement public int getId() < return id; > @XmlElement public String getName() < return name; > @XmlElement public long getPrice() < return price; > >

Things to keep in mind :

1) Your Java class must have a no-argument constructor, otherwise, JAXB will not able to marshal it. You will get the following Exception :

Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions Item does not have a no-arg default constructor. at com.sun.xml.internal.bind.v2.runtime .IllegalAnnotationsException$Builder.check(Unknown Source) at com.sun.xml.internal.bind.v2.runtime .JAXBContextImpl.getTypeInfoSet(Unknown Source) at com.sun.xml.internal.bind.v2.runtime .JAXBContextImpl.init>(Unknown Source) at com.sun.xml.internal.bind.v2.runtime .JAXBContextImpl.init>(Unknown Source) at com.sun.xml.internal.bind.v2.runtime. JAXBContextImpl$JAXBContextBuilder.build(Unknown Source) at com.sun.xml.internal.bind.v2.ContextFactory. createContext(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at javax.xml.bind.ContextFinder.newInstance(Unknown Source) at javax.xml.bind.ContextFinder.newInstance(Unknown Source) at javax.xml.bind.ContextFinder.find(Unknown Source) at javax.xml.bind.JAXBContext.newInstance(Unknown Source) at javax.xml.bind.JAXBContext.newInstance(Unknown Source)

2) Always remember to annotate your Java class with @XmlRootElement annotation, this would be your main tag in XML and each property using @XmlElement , they will appear as child element of the main tag.

That’s all about how to convert Java Object to XML. In next tutorial you will learn how to do unmarshalling i.e. converting an XML back to Java object. Even though you might know about various XML parsers e.g. DOM, SAX and StAX, its good to know JAXP and JAXB as well. As Java and XML go hand and hand, they add another tool into the Java developer’s arsenal.

If you are looking for some books to learn XML processing in Java, you can always refer core Java volume 2 for basic knowledge. It will give you nice overview of different parser, XML binding and XPath, but if you want to learn more in-depth then you can refer Java and XML by Brett McLaughlin. It’s another good book to learn about XML processing in Java.

Источник

JAXB Write Java Object to XML Example

Java example to write Java object to XML. Information stored in Java objects fields can written into XML file or simply XML string as well.

1) Convert Java Object to XML String

To write Java object to XML String , first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations.

Now get the Marshaller instance from JAXBContext . It’s marshal() method marshals Java object into XML. Now this XML can be written to different outputs e.g. string, file or stream.

package com.howtodoinjava.demo; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JaxbExample < public static void main(String[] args) < //Java object. We will convert it to XML. Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT")); //Method which uses JAXB to convert object to XML jaxbObjectToXML(employee); >private static void jaxbObjectToXML(Employee employee) < try < //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); //Create Marshaller Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Required formatting?? jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //Print XML String to Console StringWriter sw = new StringWriter(); //Write XML to StringWriter jaxbMarshaller.marshal(employee, sw); //Verify XML Content String xmlContent = sw.toString(); System.out.println( xmlContent ); >catch (JAXBException e) < e.printStackTrace(); >> >

2) Convert Java Object to XML File

Writing XML to file is very similar to above example. You only need to provide XML file location where you want to write the file.

package com.howtodoinjava.demo; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JaxbExample < public static void main(String[] args) < //Java object. We will convert it to XML. Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT")); //Method which uses JAXB to convert object to XML jaxbObjectToXML(employee); >private static void jaxbObjectToXML(Employee employee) < try < //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); //Create Marshaller Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Required formatting?? jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //Store XML to File File file = new File("employee.xml"); //Writes XML file to file-system jaxbMarshaller.marshal(employee, file); >catch (JAXBException e) < e.printStackTrace(); >> >

If you want to read the XML from file to Java object again, then use this method.

String fileName = "employee.xml"; //Call method which read the XML file above jaxbXmlFileToObject(fileName); private static void jaxbXmlFileToObject(String fileName) < File xmlFile = new File(fileName); JAXBContext jaxbContext; try < jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile); System.out.println(employee); >catch (JAXBException e) < e.printStackTrace(); >>
Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

Drop me your questions in comments section.

Источник

Оцените статью