Generic method from XML String to Object - Android XML

Android examples for XML:JAXB

Description

Generic method from XML String to Object

Demo Code


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

import javax.xml.bind.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        String xml = "java2s.com";
        Class valueType = String.class;
        System.out.println(fromXML(xml, valueType));
    }//from  ww w .  j a  v  a2 s  .co  m

    @SuppressWarnings("unchecked")
    public static <T> T fromXML(String xml, Class<T> valueType) {
        try {
            JAXBContext context = JAXBContext.newInstance(valueType);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}

Related Tutorials