zoukankan      html  css  js  c++  java
  • 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;

    }

  • 相关阅读:
    Python Virtualenv 虚拟环境
    二叉树的左视图和右视图
    Vxlan简介
    2、程序的基本结构
    chef cookbook 实战
    eclipse 搭建ruby环境
    linux 安装软件出现/tmp 磁盘不足时 解决方案
    Python 可变对象与不可变对象
    Chapter 4-5
    Chapter 3
  • 原文地址:https://www.cnblogs.com/wangrongchen/p/11353545.html
Copyright © 2011-2022 走看看