Jaxb

xjc -d D:\eclipse\workspace\JaxbTest\src -p "edu.jlu.xml" "D:\eclipse\workspace\JaxbTest\schema\messages.xsd"

其中D:\eclipse\workspace\JaxbTest\src为原文件的目录
edu.jlu.xml为生成Java类的包名
D:\eclipse\workspace\JaxbTest\schema\messages.xsd为xml schema文件的路径

 

public class Test {

 private static String filePath = "";
 private static SchemaFactory schFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
 private static javax.xml.validation.Schema sch;

 public static void main(String[] args) {
  try {
   sch = schFactory.newSchema(new File("D:\eclipse\workspace\JaxbTest\schema\messages.xsd"));
   toXml();
   toObj();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 private static void toXml() throws Exception {
 //
  JAXBContext jaxbContext = JAXBContext.newInstance(T.class);
  // marshal 整理,编列,元帅的意思
  Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//  jaxbMarshaller.setSchema(sch);
  // format, make every element keep a separate line.
  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  // output --> file
  File file = new File(filePath);
  jaxbMarshaller.marshal(object, file);
  
  // output --> console
  jaxbMarshaller.marshal(object, System.out);
 }
 
 private static void toObj() throws Exception {
  File file = new File(filePath);
  JAXBContext jaxbContext = JAXBContext.newInstance(T.class);
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  Object scbml = jaxbUnmarshaller.unmarshal(file);
  System.out.println(scbml.getPayload().getPayloadContent());
 }

 }

posted @ 2015-08-05 15:21  tang9139  阅读(247)  评论(0编辑  收藏  举报