Generic to Unmarshall XML to an Object - Java XML

Java examples for XML:JAXB

Description

Generic to Unmarshall XML to an Object

Demo Code


//package com.java2s;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import javax.xml.bind.Unmarshaller;

public class Main {
    public static void main(String[] argv) throws Exception {
        String xml = "java2s.com";
        Class cla = String.class;
        System.out.println(fromXML(xml, cla));
    }//from  ww w .ja va  2  s .com

    @SuppressWarnings("unchecked")
    public static <T> T fromXML(String xml, Class<T> cla) {
        try {
            JAXBContext context = JAXBContext.newInstance(cla);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related Tutorials