用法参考:
Document document = (Document) JAXBTool.unmarshalXml("D:\\temp\\LightRequirmentDocument1.3.xml", Document.class);
JAXBTool.marshalToXml(Document.class, document, "D:\\temp\\test.xml");
源码:
package owngeftable.Tools;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class JAXBTool
{
public static Object unmarshalXml(String path, Class className)
{
Object result = null;
try
{
File file = new File(path);
JAXBContext jaxbContext = JAXBContext.newInstance(className);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
result = jaxbUnmarshaller.unmarshal(file);
}
catch (JAXBException e)
{
e.printStackTrace();
}
return result;
}
public static void marshalToXml(Class className, Object root,String filePath)
{
try
{
File file = new File(filePath);
JAXBContext jaxbContext = JAXBContext.newInstance(className);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(root, file);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}