XML String To Pojo via JAXB - Java XML

Java examples for XML:JAXB

Description

XML String To Pojo via JAXB

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 xmlStr = "java2s.com";
        Class cla = String.class;
        System.out.println(XMLStrToPojo(xmlStr, cla));
    }/* w  w  w  .j  av  a 2  s . co  m*/

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

Related Tutorials