Java XML JAXB String to Object fromXml(File xmlPath, Class type)

Here you can find the source of fromXml(File xmlPath, Class type)

Description

from Xml

License

Open Source License

Declaration

public static <T> T fromXml(File xmlPath, Class<T> type) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

import javax.xml.bind.Unmarshaller;
import java.io.*;

public class Main {
    private static final String ENCODING = "GBK";

    public static <T> T fromXml(File xmlPath, Class<T> type) {
        BufferedReader reader = null;
        StringBuilder sb = null;/*ww w.  j  ava  2  s .  c o m*/
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(xmlPath), ENCODING));
            String line = null;
            sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException(e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
        return fromXml(sb.toString(), type);
    }

    public static <T> T fromXml(String xml, Class<T> type) {
        if (xml == null || xml.trim().equals("")) {
            return null;
        }
        JAXBContext jc = null;
        Unmarshaller u = null;
        T object = null;
        try {
            jc = JAXBContext.newInstance(type);
            u = jc.createUnmarshaller();
            object = (T) u.unmarshal(new ByteArrayInputStream(xml.getBytes(ENCODING)));
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return object;
    }
}

Related

  1. fromStream(Class jaxbClass, InputStream is)
  2. fromStringToObject(String xmlString, Class xmlObjClass)
  3. fromXml(@SuppressWarnings("rawtypes") Class clazz, String stringXml)
  4. fromXML(Class clazz, InputStream is)
  5. fromXml(Class tClass, InputStream inputStream)
  6. fromXML(final byte[] data, final Class type)
  7. fromXml(final Reader reader, final Class dtoClass)
  8. fromXml(InputStream input, Class clazz)
  9. fromXml(InputStream xml, Class objectClass)