import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Marshaller;
import java.io.File;
import javax.xml.datatype.XMLGregorianCalendar;
import org.w3c.dom.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import JAXBbooks.*; // import classes generated by binding compiler

public class JAXBbooks {

  public static void main (String args[]) { try
    { // generate the context using the JAXBBooks directory
      // where the generated classes and the ObjectFactory are
      JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
      Unmarshaller unmarshaller = jc.createUnmarshaller();

      //   continue next page


      BookCollection collection =
           (BookCollection) unmarshaller.unmarshal(new File( "books.xml"));
      BookCollection.Books books = collection.getBooks();

      for (BookType book : books.getBook()) {
        System.out.println("Book details "   );
        System.out.println("Book Name: " +  book.getName().trim());
        System.out.println("Book ISBN: " +  book.getIsbn().trim());
        System.out.println("Book Price: " +  book.getPrice());
        if (book.getPromotion().getDiscount() != null)
        System.out.println("Book promotion: " +  book.getPromotion().getDiscount().trim());
        System.out.println("No of Authors " + book.getAuthors().getAuthorName().size());

        BookType.Authors authors = book.getAuthors();
        for (String authorName : authors.getAuthorName())
            System.out.println("Author Name " + authorName.trim());
        XMLGregorianCalendar date = book.getPublicationDate();
        System.out.println("Date " + date);
        for (String language: book.getLanguage())
            System.out.println("Language " + language.trim());
        // add an element to a live list:
        book.getLanguage().add("Kisuaheli");
      }

      // transform the result into a DOM and write to an XML file:
      Marshaller m = jc.createMarshaller();
      DOMResult domResult = new DOMResult();
      m.marshal(collection, domResult);
      Document doc = (Document) domResult.getNode();
      // transformer stuff is only for writing DOM tree to file/stdout
      TransformerFactory factory = TransformerFactory.newInstance();
      Source docSource = new DOMSource(doc);
      StreamResult result = new StreamResult("foo.xml");
      System.out.println("look into foo.xml for the result");
      Transformer transformer = factory.newTransformer();
      transformer.transform(docSource, result);
    } catch (Exception e) { e.printStackTrace(); }
 }}
