Java XML JAXB Unserialize loadXML(Object object, String fileNamePath)

Here you can find the source of loadXML(Object object, String fileNamePath)

Description

load XML

License

Open Source License

Declaration

public static Object loadXML(Object object, String fileNamePath) 

Method Source Code

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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import java.io.IOException;

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

import javax.xml.bind.Unmarshaller;

public class Main {
    public static Object loadXML(Object object, String fileNamePath) {
        Unmarshaller unmarshaller = createUnmarshaller(object);
        Object loaded = null;/*  w ww .j  a  va 2 s . co  m*/
        File fileXML = createFile(fileNamePath);

        if (fileXML.length() > 0) {
            try {
                loaded = unmarshaller.unmarshal(new FileReader(fileNamePath));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JAXBException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return loaded;
    }

    @SuppressWarnings("rawtypes")
    private static Unmarshaller createUnmarshaller(Object object) {
        Class objectClass = object.getClass();

        if (objectClass.getSimpleName().equals("Class")) {
            objectClass = (Class) object;
        }

        JAXBContext context;
        Unmarshaller unmarshaller = null;
        try {
            context = JAXBContext.newInstance(objectClass);
            unmarshaller = context.createUnmarshaller();
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return unmarshaller;
    }

    private static File createFile(String fileNamePath) {
        File file = new File(fileNamePath);

        if (!file.exists()) {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return file;
    }
}

Related

  1. load(InputStream input, Class type)
  2. loadObject(Class typeClass, URL path)
  3. loadObject(Path path, Class clazz)
  4. loadXML(Class type, File sourceFile)
  5. loadXml(File file, Class requireType)
  6. loadXMLFromString(Object object, String line)
  7. parse(final Class clazz, final InputStream inputStream)
  8. parseIsoDate(String lexicalDate)
  9. parseJaxb(Class cls, InputStream in)