What is Marshalling ? Marshalling example.






 Marshalling:


Converting java object to XML.

In other words, marshalling means producing a stream of bytes to re-build the object.And this is a read only operation, as we can not modify an object while marshalling.


Earlier we studied about the unmarshalling where we already had the XML file.

But in its complimentary, we will be generating XML file as we will have the object.

The output XML will have a book catalog and list of books including their author and description samples.


Client.java

-------------------------------------- 

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Client{
       public static void main(String[] args) throws JAXBException {
              //creating catalog object
              Catalog catalog = new Catalog();
             
              //number of books list initialised
              Book[] book=new Book[2];
             
              Book book1 = new Book();
              Book book2 = new Book();
             
              book1.setAuthor("Author 1");
              book1.setDescription("Book Description 1");
             
              book2.setAuthor("Author 2");
              book2.setDescription("Book Description 2");
             
              //creating books list
              book[0]=book1;
              book[1]=book1;
             
              //adding or setting books list to catalog
              catalog.setBook(book);
             
              JAXBContext jaxbContext = JAXBContext.newInstance(Catalog.class);
              Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

              jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

              //creating XML file catalog.xml, by default it will get generated
              //in your project, press F5 to see file in project after running once
             
              jaxbMarshaller.marshal(catalog, new File("catalog.xml"));
              jaxbMarshaller.marshal(catalog, System.out);
       }
}

Output :

----------------------------------------- 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<catalog>
    <book>
        <author>Author 1</author>
        <description>Book Description 1</description>
    </book>
    <book>
        <author>Author 1</author>
        <description>Book Description 1</description>
    </book>
</catalog>


No comments:

Post a Comment

Fixing yum command on linux

You may find yourself having to fix more packages. So you can just remove everything you had installed via  pip and reinstall everythin...