Nov 15, 2014

Java Architecture For XML Binding(Marshaling and Unmarshaling)

In This We Are Focusing On Communication Between Java Application and XML Files.
First Of All Make Sure Your Machine Is Setup With Java Development Environment.

In This Lesson Will Do Following Tasks.

1. Creating A Simple XML File
2. Generating XSD File For XML File
3. Running JAXB Compiler To Genarate Java Classes
4. Unmarshal(XML To Objects) & Marshaling(Objects To XML)
5. Running The Project

Before Starting Make Sure You Have Downloaded The "jaxb-api-2.1" & Setup The ClassPath For That.If Everything Done Lets Do Begin The Work.

1. Creating A Simple XML File
First Create A XML File As You Want, But Make It With Many Results.
I'm Going To Use XML Related To Library.

Library.xml 
<?xml version="1.0"?>
<Library>
<Book>
<Title>My Life and Times</Title>
<Author>Paul McCartney</Author>
<Date>1998</Date>
<ISBN>1-56592-235-2</ISBN>
<Publisher>McMillin Publishing</Publisher>
</Book>
<Book>
<Title>Illusions The Adventures of a Reluctant Messiah</Title>
<Author>Richard Bach</Author>
<Date>1977</Date>
<ISBN>0-440-34319-4</ISBN>
<Publisher>Dell Publishing Co.</Publisher>
</Book>
<Book>
<Title>The First and Last Freedom</Title>
<Author>J. Krishnamurti</Author>
<Date>1954</Date>
<ISBN>0-06-064831-7</ISBN>
<Publisher>Harper &amp; Row</Publisher>
</Book>

</Library>


2. Generating XSD File For XML File
Now We Need To Get The XSD File For This XML.Rather Going For A Coding To Do This, Simply Google It "XML To XSD". You Will Find Many XML To XSD Converters Online.
I Have Used One Of Them & Converted My Library.xml To Library.xsd

Library.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
  <xs:element name="Library">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Book" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Title" type="xs:string"></xs:element>
                            <xs:element name="Author" type="xs:string"></xs:element>
                            <xs:element name="Date" type="xs:int"></xs:element>
                            <xs:element name="ISBN" type="xs:string"></xs:element>
                            <xs:element name="Publisher" type="xs:string"></xs:element>
                        </xs:sequence>
</xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>


3. Running JAXB Compiler To Genarate Java Classes
First Create A Folder Inside Your Project Folder And Name It As JAXB.
Open A Command Prompt And Go To The Relevant Folder Using.
To Generate Java Classes For This XML File Run The Following Command In Command Prompt.

xjc -d JAXB Library.xsd

After Run This You Will Get The Java Classes Inside The Folder JAXB.
Following Are The Classes Which I Got.

Library.java
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "book"
})
@XmlRootElement(name = "Library")
public class Library {

    @XmlElement(name = "Book", required = true)
    protected List<Library.Book> book;

    public List<Library.Book> getBook() {
        if (book == null) {
            book = new ArrayList<Library.Book>();
        }
        return this.book;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "title",
        "author",
        "date",
        "isbn",
        "publisher"
    })
    public static class Book {

        @XmlElement(name = "Title", required = true)
        protected String title;
        @XmlElement(name = "Author", required = true)
        protected String author;
        @XmlElement(name = "Date")
        protected int date;
        @XmlElement(name = "ISBN", required = true)
        protected String isbn;
        @XmlElement(name = "Publisher", required = true)
        protected String publisher;

        public String getTitle() {
            return title;
        }

        public void setTitle(String value) {
            this.title = value;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String value) {
            this.author = value;
        }

        public int getDate() {
            return date;
        }

        public void setDate(int value) {
            this.date = value;
        }

        public String getISBN() {
            return isbn;
        }

        public void setISBN(String value) {
            this.isbn = value;
        }

        public String getPublisher() {
            return publisher;
        }

        public void setPublisher(String value) {
            this.publisher = value;
        }
    }
}

ObjectFactory.java
import javax.xml.bind.annotation.XmlRegistry;

@XmlRegistry
public class ObjectFactory {

    public ObjectFactory() {
    }

    public Library createLibrary() {
        return new Library();
    }

    public Library.Book createLibraryBook() {
        return new Library.Book();
    }
}

4. Unmarshal(XML To Objects) & Marshaling(Objects To XML)
Create Following Java Class Inside The JAXB FolderTo Do The Un-Marshaling and Marshaling.

Main.java
import java.io.File;
import java.io.FileReader;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

class Main { 

    public static void main(String args[]){

try{
//Creating The Context
JAXBContext jaxbcontext = JAXBContext.newInstance(Library.class);
Unmarshaller unmarshaller = jaxbcontext.createUnmarshaller();

//Unmarshaling Library XML File
Library library = (Library)unmarshaller.unmarshal(new FileReader("Library.xml"));
List<Library.Book> booklist = library.getBook();

//Printing Library Book Details
System.out.println("\nUnMarshalling :: Current XML File\n\n");
System.out.println("\n~~ Libraray Book Details ~~\n");
System.out.println("____________________________________________________");
int iBookCount = 1;
for (Library.Book book : booklist) {
System.out.println("Book No :" + iBookCount++);
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Date: " + book.getDate());
System.out.println("ISBN: " + book.getISBN());
System.out.println("Publisher: " + book.getPublisher());
System.out.println("____________________________________________________");
}

//Adding A New Book To The Library
Library.Book newBook1 = new Library.Book();
newBook1.setTitle("Learning Java in 21 Days");
newBook1.setAuthor("Sam De Costa");
newBook1.setDate(2012);
newBook1.setISBN("978-0060554736");
newBook1.setPublisher("Sun Micro Systems");
booklist.add(newBook1);

//Adding A New Book To The Library
Library.Book newBook2 = new Library.Book();
newBook2.setTitle("How Te Be A Good Programmer");
newBook2.setAuthor("Nifal Nizar");
newBook2.setDate(2014);
newBook2.setISBN("1245-0060-5547");
newBook2.setPublisher("ADVANCE PUBLISHERS");
booklist.add(newBook2);

//Printing New Library Book Details
System.out.println("\n~~ New Libraray Book Details ~~\n");
System.out.println("____________________________________________________");
iBookCount = 1;
for (Library.Book book : booklist) {
System.out.println("Book No :" + iBookCount++);
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Date: " + book.getDate());
System.out.println("ISBN: " + book.getISBN());
System.out.println("Publisher: " + book.getPublisher());
System.out.println("____________________________________________________");
}

//Creating Library Object To Write To The XML File
ObjectFactory objectfactory = new ObjectFactory();
Library mylibrary = objectfactory.createLibrary();
for (Library.Book book : booklist) {
mylibrary.getBook().add(book);
}

//Marshalling
Marshaller marshaller = jaxbcontext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(mylibrary, new File("Library.xml"));

//Printing New XML File
System.out.println("\n\nMarshaling Done");
                        System.out.println("This Is The Newest xml File\n");
marshaller.marshal(mylibrary, System.out);

}

catch(Exception e){
System.out.println(e.toString());
}
}

}


5. Running The Project
Go To Folder JAXB In The Command Prompt.
Compile All The Classes Using Command *.java
Run The Project Using Command java Main

You Will Get The Output.

Enjoy Coding...

No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...