Java XML JAXB String to Object fromXml(InputStream input, Class clazz)

Here you can find the source of fromXml(InputStream input, Class clazz)

Description

from Xml

License

Apache License

Declaration

@SuppressWarnings("unchecked")
    public static <T> T fromXml(InputStream input, Class<T> clazz) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayInputStream;

import java.io.InputStream;
import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import javax.xml.bind.Unmarshaller;

public class Main {
    public static final String CHARSET = "UTF-8";

    @SuppressWarnings("unchecked")
    public static <T> T fromXml(InputStream input, Class<T> clazz) {

        try {//from  w  w  w .ja va2  s. co  m
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();

            return (T) unmarshaller.unmarshal(new InputStreamReader(input, CHARSET));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> T fromXml(String xmlStr, Class<T> clazz) {
        return fromXml(new ByteArrayInputStream(xmlStr.getBytes(Charset.forName(CHARSET))), clazz);
    }
}

Related

  1. fromXML(Class clazz, InputStream is)
  2. fromXml(Class tClass, InputStream inputStream)
  3. fromXml(File xmlPath, Class type)
  4. fromXML(final byte[] data, final Class type)
  5. fromXml(final Reader reader, final Class dtoClass)
  6. fromXml(InputStream xml, Class objectClass)
  7. fromXml(Reader xml, Class clazz)
  8. fromXml(String responseBody, Class c)
  9. fromXml(String xml, Class clazz)