[New] Added XmlHelper.parseAndUnmarshalFile()

This commit is contained in:
Robert von Burg 2018-12-18 14:33:29 +01:00
parent b0f85ed76e
commit 94b0dd4f5a
1 changed files with 34 additions and 0 deletions

View File

@ -15,6 +15,9 @@
*/
package li.strolch.utils.helper;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.parsers.*;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
@ -129,6 +132,37 @@ public class XmlHelper {
}
}
/**
* <p>Helper method to parse the given {@link File} using JAXB to the given object type</p>
*
* <p><b>Note:</b> The passed class must have the {@link XmlRootElement} annotation!</p>
*
* @param file
* the file to parse
* @param clazz
* the class for the returning object type
* @param <T>
* the type of object to return
*
* @return the parsed object
*/
public static <T> T parseAndUnmarshalFile(File file, Class<T> clazz) {
try (FileInputStream fin = new FileInputStream(file)) {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
@SuppressWarnings("unchecked")
T o = (T) unmarshaller.unmarshal(fin);
return o;
} catch (Exception e) {
throw new IllegalStateException("Failed to parse file " + file.getAbsolutePath() + " to object " + clazz,
e);
}
}
/**
* Writes an {@link Element} to an XML file on the file system
*