/** * $Id: UsingJAXBTest3.java,v 1.1 2003/01/01 03:18:32 bhakti Exp $ * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. */ package test.jaxb; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.Validator; import java.io.File; import java.io.FileOutputStream; import java.util.List; /** * This shows how to use JAXB to update the unmarshalled content tree * then marshal it back to xml document */ public class UsingJAXBTest3 { public static void main (String args[]) { try { JAXBContext jc = JAXBContext.newInstance("test.jaxb"); ObjectFactory objFactory = new ObjectFactory(); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setValidating(true); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT , new Boolean(true)); Validator validator = jc.createValidator(); Collection collection= (Collection) unmarshaller.unmarshal(new File( "books.xml")); CollectionType.BooksType booksType = collection.getBooks(); List bookList = booksType.getBook(); for( int i = 0; i < bookList.size();i++ ) { test.jaxb.BookType book =(test.jaxb.BookType) bookList.get(i); if ( book.getISBN()==522965L) { BookType.PromotionType promotionType = objFactory. createBookTypePromotionType(); promotionType.setDiscount("Spring Sale! Save 30% on all purchases"); book.setPromotion(promotionType); System.out.println("Updated the Book promotion for \""+ book.getName().trim() +"\" to \n\"" + book.getPromotion(). getDiscount().trim()+"\""); } } System.out.println("\nValidator returned: " + validator.validate(collection)+" after changing the promotion"); System.out.println("See output in jaxbOutput3.xml"); marshaller.marshal(collection, new FileOutputStream("jaxbOutput3.xml")); }catch (Exception e ) { e.printStackTrace(); } } }