Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Marshalling and Unmarshalling in Java

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 563
    Comment on it

    JAXB is Java Architecture for XML Binding which allows to map Java objects to XML and XML to Java objects.

    Marshalling example : Converting a Java object into a XML file.

       
        import java.io.File;
        import javax.xml.bind.JAXBContext;
        import javax.xml.bind.JAXBException;
        import javax.xml.bind.Marshaller;
    
        public class JAXBExample {
            public static void main(String[] args) {
    
              Customer customer = new Customer();
              customer.setId(100);
              customer.setName("FindNerd");
              customer.setAge(29);
    
              try {
    
                File file = new File("C:\\XMLname.xml");
                JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    
                // output pretty printed
                jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    
                jaxbMarshaller.marshal(customer, file);
                jaxbMarshaller.marshal(customer, System.out);
    
                  } catch (JAXBException e) {
                e.printStackTrace();
                  }     
            }
        }
    

    Unmarshalling example : Converting XML content into a Java Object.

    import java.io.File;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Unmarshaller;
    
    public class JAXBExample {
        public static void main(String[] args) {
    
         try {
    
            File file = new File("C:\\XMLname.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
            System.out.println(customer);
    
          } catch (JAXBException e) {
            e.printStackTrace();
          }
    
        }
    }
    
    

    Refrences

    JaxB Refrence

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: