From 94b0dd4f5a381c0e7ac7cd155335b3cbff882386 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Tue, 18 Dec 2018 14:33:29 +0100 Subject: [PATCH] [New] Added XmlHelper.parseAndUnmarshalFile() --- .../li/strolch/utils/helper/XmlHelper.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/li.strolch.utils/src/main/java/li/strolch/utils/helper/XmlHelper.java b/li.strolch.utils/src/main/java/li/strolch/utils/helper/XmlHelper.java index 0bab0fc6c..68a19836f 100644 --- a/li.strolch.utils/src/main/java/li/strolch/utils/helper/XmlHelper.java +++ b/li.strolch.utils/src/main/java/li/strolch/utils/helper/XmlHelper.java @@ -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 { } } + /** + *

Helper method to parse the given {@link File} using JAXB to the given object type

+ * + *

Note: The passed class must have the {@link XmlRootElement} annotation!

+ * + * @param file + * the file to parse + * @param clazz + * the class for the returning object type + * @param + * the type of object to return + * + * @return the parsed object + */ + public static T parseAndUnmarshalFile(File file, Class 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 *