You can save coding time by automating this process in JAXB:
Create an XML schema for your XML using the link below to save it as output.xsd file: http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx
Run the batch script file (name it output.bat ) below from the project root folder (.) Using the JDK, since only the JDK has the xjc.exe tool (fill in the required data):
"C:\Program Files\Java\jdk1.6.0_24\bin\xjc.exe" -p %1 %2 -d %3
Where...
syntax: output.bat %1 %2 %3 %1 = target package name %2 = full file path name of the generated XML schema .xsd %3 = root source folder to store generated JAXB java files
Example:
Let the project folder be organized as follows:
. \_src
Run the following command at a command prompt (.):
output.bat com.project.xml .\output.xsd .\src
It will create several files:
. \_src \_com \_project \_xml |_ObjectFactory.java |_Output.java
You can then create some useful methods below to manipulate Output objects:
private JAXBContext jaxbContext = null; private Unmarshaller unmarshaller = null; private Marshaller marshaller = null; public OutputManager(String packageName) { try { jaxbContext = JAXBContext.newInstance(packageName); unmarshaller = jaxbContext.createUnmarshaller(); marshaller = jaxbContext.createMarshaller(); } catch (JAXBException e) { } } public Output loadXML(InputStream istrm) { Output load = null; try { Object o = unmarshaller.unmarshal(istrm); if (o != null) { load = (Output) o; } } catch (JAXBException e) { JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); } return load; } public void saveXML(Object o, java.io.File file) { Output save = null; try { save = (Output) o; if (save != null) { marshaller.marshal(save, file); } } catch (JAXBException e) { JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); } } public void saveXML(Object o, FileOutputStream ostrm) { Output save = null; try { save = (Output) o; if (save != null) { marshaller.marshal(save, ostrm); } } catch (JAXBException e) { JOptionPane.showMessageDialog(null, e.getLocalizedMessage(), e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); } }