Sie sind auf Seite 1von 2

JAXB Marshalling and Un marshalling:

package com;

import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.Iterator;
import java.util.List;

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

import com.Books.Book;

public class Test {

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


Books books=new Books();
List<Book> bookList=books.getBook();

Book bookObj=new Book();


bookObj.setBid(new BigInteger("100"));
bookObj.setAuthor("RAJA");
bookObj.setCost(new BigDecimal(10.236).setScale(3,
RoundingMode.HALF_EVEN));

bookList.add(bookObj);

/***
* Marshalling
*/

JAXBContext context=JAXBContext.newInstance(Books.class);
Marshaller marshallerObj=context.createMarshaller();
marshallerObj.marshal(books, new File("d:/output/result.xml"));
System.out.println("done");

/***
* Un marshalling
*/

Unmarshaller unmarshallerObj=context.createUnmarshaller();
Books books1=(Books)unmarshallerObj.unmarshal(new
File("d:/output/result.xml"));

List<Book> listBook=books1.getBook();
Iterator<Book> iterator=listBook.iterator();

while (iterator.hasNext()) {
Books.Book book = (Books.Book) iterator.next();
System.out.println(book.getBid());
System.out.println(book.getAuthor());
System.out.println(book.getCost());
}

}
}
Sample.xsd

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/sample"
xmlns:tns="http://www.example.org/sample"
elementFormDefault="qualified">

<xs:element name="books">
<xs:complexType >
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="bid" type="xs:integer"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="cost" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

*** Use JAXB Tool to generate java classes

Command : xjc p com sample.xsd d Raghu

Xjc -p <package-name> <filename.xsd> d <folder name>

Download Location for JAXB Tool : https://java.net/downloads/jaxb/releases/

Das könnte Ihnen auch gefallen