XML操作处理

需要jar包 xml-resolver.jar  xmlschema-core.jar

//把对象转成String类型的xml

public stratic String convertoxml(Object obj){

  //创建输出流 

  StringWriter sw = new StringWriter();

  //转换  

  JAXBContext context = JAXBContext.newInstance(obj.getClass());

  Marshaller marshaller = context.createMarshaller();

  //格式化xml

  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);

  //对象转成输出流形式的xml

  marshaller.marshal(obj,sw);

  return sw.toString();

}

//将对象根据路径转xml文件

public static void convertToXml(Object obj,String path){

  JAXBContext context = JAXBContext.newInstance(obj.class());

  Marshaller marshaller = context.createMarshaller();

  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);  

  FileWrite fw = null;

  fw = new FileWrite;

  marshaller.marshal(obj,fw);

}

//将String类型的xml转成对象

public static Object convertXmlStrToObject(Class<?> clazz,String xmlstr){

  Object obj =null;

  JAXBContext context = JAXBContext.newInstance(clazz);

  //将xml转成对象的核心接口

  Unmarsharller unmarshaller = context.createUnmarshaller();

  StringReader sr = new StringReader(xmlstr);

  obj = unmarshaller.unmarshal(sr);

  return obj;

}

//将file类型xml转成对象

public static Object convertXmlFileToObject(Class<?> clazz,String path){

  Object xobj =null;  

  JAXBContext context = JAXBContext.newInstance(obj.class());  

  Unmarsharller unmarshaller = context.createUnmarshaller();

  FileReader fr =null;

  fr = new FileReader(path);

  xobj = unmarshaller.unmarshal(fr);

  return xobj;

}

原文地址:https://www.cnblogs.com/wangrongchen/p/11353545.html