Total Pageviews

Sunday 1 April 2012

Unmarshalling from XML file and marshalling to XML file

            ObjectFactory of = new ObjectFactory();
            FlightInfo sh = of.createFlightInfo();
            //Unmarshalling
            JAXBContext ctx = JAXBContext.newInstance(sh.getClass().getPackage().getName());
            Unmarshaller unm = ctx.createUnmarshaller();
            sh= (FlightInfo)unm.unmarshal(new File("flight.xml"));

           //do something with object sh

            //Marshalling
            try {               
                javax.xml.bind.Marshaller marshaller = ctx.createMarshaller();
                marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");
                marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                marshaller.marshal(sh, new FileOutputStream(new File("flight.xml")));
            } catch (javax.xml.bind.JAXBException ex) {
            // Handle exception
            java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex);
            }    

No comments:

Post a Comment