from Xml to Object using JAXB - Android XML

Android examples for XML:JAXB

Description

from Xml to Object using JAXB

Demo Code


//package com.java2s;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        File xmlPath = new File("Main.java");
        Class type = String.class;
        System.out.println(fromXml(xmlPath, type));
    }//from  w  ww  . j a v  a2  s  .co m

    private static final String ENCODING = "GBK";

    public static <T> T fromXml(File xmlPath, Class<T> type) {
        BufferedReader reader = null;
        StringBuilder sb = null;
        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 Tutorials