Friday, September 2, 2016

Creating an Object to XML and XML to Object to using JAXB marshalling

JAXB stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file

Create a Person Object for this object to convert to / from XML , we should annotate with JAXB annotation .Root element/Class with @XmlRootElement and @XmlElement for variables.


Using below snippet code we can create a file from Object to XML ,using JAXBMarshaller

        Person person = new Person();
        person.setFirstName("Steven");
        person.setLastName("Kinggfdgdf);
        person.setPhone("515.123.4567);
        person.setEmail("SKING);

        try {
            File file = new File("C:\\file.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(person, file);
        } catch (PropertyException pe) {
            pe.printStackTrace();
        } catch (JAXBException jaxbe) {
            jaxbe.printStackTrace();
        }

We can also create a String from Object to XML , here we will use java.io.StringWriter 

        Person person = new Person();
        person.setFirstName("Steven");
        person.setLastName("Kinggfdgdf);
        person.setPhone("515.123.4567);
        person.setEmail("SKING);

        try {
            StringWriter sw = new StringWriter();
            JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(person, sw);
            System.out.println(sw.toString());
        } catch (PropertyException pe) {
            pe.printStackTrace();
        } catch (JAXBException jaxbe) {
            jaxbe.printStackTrace();
        }

Output




Below snippet code is to create a Object from XML using JAXBUnmarshaller

            File file = new File("C:\\file.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Person person = (Person)jaxbUnmarshaller.unmarshal(file);
            System.out.println(person);

Output

Person [email=SKING, firstName=Steven, lastName=Kinggfdgdf, phone = 515.123.4567]


No comments:

Post a Comment