JAXB序列化和反序列化XML源码(可直接使用)

来源:互联网 发布:json格式解析 编辑:程序博客网 时间:2024/05/17 23:42

用法参考

 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();
    }
}
}

原创粉丝点击