Convert XML to Object using JAXB - Java XML

Java examples for XML:JAXB

Description

Convert XML to Object using JAXB

Demo Code


//package com.java2s;

import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String xmlText = "java2s.com";
        Class contClass = String.class;
        System.out.println(fromXML(xmlText, contClass));
    }//  w w w  .  j  av  a 2s  .  c o m

    public static <T> T fromXML(String xmlText, Class<T> contClass) {
        try {
            return (T) JAXBContext.newInstance(contClass)
                    .createUnmarshaller()
                    .unmarshal(new StringReader(xmlText));
        } catch (JAXBException ex) {
            System.out.println(ex.getMessage());
            return null;
        }
    }
}

Related Tutorials