zoukankan      html  css  js  c++  java
  • java实体 和 xml相互转换

    参考:

    https://blog.csdn.net/LookForDream_/article/details/88884316

    https://zhuchengzzcc.iteye.com/blog/1838702

    核心代码

    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.StringReader;
    import java.io.StringWriter;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
     
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import dns.rsdnscount.entity.SlaveEntity;
    import dns.rsdnscount.entity.SlavesEntity;
     
    
    public class XmlUtils {
     
        private static Logger logger = LoggerFactory.getLogger(XmlUtils.class);
        
        public static void main(String[] args) {
    /*        SlavesEntity list=new SlavesEntity();
            
            SlaveEntity ent=new SlaveEntity();
            ent.setHost("master");
            ent.setPort("3306");
            ent.setUserName("user1");
            ent.setRemoteResultPath("/home/user");
            list.getEntitys().add(ent);
            SlaveEntity ent2=new SlaveEntity();
            ent2.setHost("master2");
            ent2.setPort("3306");
            ent2.setUserName("user2");
            ent2.setRemoteResultPath("/home/user2");
            list.getEntitys().add(ent2);
            String xxx=convertToXml(list,"utf-8",true);
            System.out.println(xxx);*/
            try {
                SlavesEntity ents=convertToJava(new File("conf/slaves.xml"), SlavesEntity.class);
            for (SlaveEntity ent : ents.getEntityList()) {
                System.out.println(ent);
            }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
        }
     
        /**
         * JavaBean转换成xml
         * 
         * @param obj
         * @param encoding
         * @return
         */
        public static String convertToXml(Object obj, String encoding, boolean format) {
            String result = null;
            StringWriter writer = null;
            try {
                JAXBContext context = JAXBContext.newInstance(obj.getClass());
                Marshaller marshaller = context.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
                writer = new StringWriter();
                marshaller.marshal(obj, writer);
                result = writer.toString();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (writer != null){
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
     
        /**
         * xml转换成JavaBean
         * 
         * @param xml
         * @param c
         * @return
         */
        @SuppressWarnings("unchecked")
        public static <T> T convertToJava(String xml, Class<T> c) {
            if (xml == null || xml.equals(""))
                return null;
            T t = null;
            StringReader reader = null;
            try {
                JAXBContext context = JAXBContext.newInstance(c);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                reader = new StringReader(xml);
                t = (T) unmarshaller.unmarshal(reader);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (reader != null)
                    reader.close();
            }
            return t;
        }
        
        @SuppressWarnings("unchecked")
        public static <T> T convertToJava(File filePath, Class<T> c) throws IOException {
            if (!filePath.exists())
                return null;
            T t = null;
            FileReader reader = null;
            try {
                JAXBContext context = JAXBContext.newInstance(c);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                reader = new FileReader(filePath);
                t = (T) unmarshaller.unmarshal(reader);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (reader != null)
                    reader.close();
            }
            return t;
        }
    }

    实体类

    import java.util.LinkedList;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlElementWrapper;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name="slavesList")
    public class SlavesEntity{
        
        @XmlElementWrapper(required=true,name="entitys")
        @XmlElement(name="entity")
        LinkedList<SlaveEntity> entityList=new LinkedList<SlaveEntity>();
    
        public LinkedList<SlaveEntity> getEntityList() {
            return entityList;
        }
    
        public void setEntityList(LinkedList<SlaveEntity> entityList) {
            this.entityList = entityList;
        }
        
    }
    
    import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(propOrder = { "host", "port", "userName", "remoteResultPath", }) public class SlaveEntity { String host; String userName; String port; @XmlElement(required=false,name="remoteResultPath") String remoteResultPath; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getRemoteResultPath() { return remoteResultPath; } public void setRemoteResultPath(String remoteResultPath) { this.remoteResultPath = remoteResultPath; } @Override public String toString() { return "SlaveEntity [host=" + host + ", userName=" + userName + ", port=" + port + ", remoteResultPath=" + remoteResultPath + "]"; } }
  • 相关阅读:
    linux 备份当前文件
    zz Apache 2.2.15 + PHP 5.3.2+ mysql windows环境配置
    zz iframe父子窗口间js方法调用
    批处理命令里获取本机的机器名
    Cache Concurrency Problem False Sharing
    因为添加assembly到GAC引起的Windows Azure Web Role部署失败
    求数组中满足a[i]<a[j]的相距最远的元素
    Dispose模式
    比较汇编指令 LEA 和 MOV
    读写Unicode字符串(UTF8,UTF16…)
  • 原文地址:https://www.cnblogs.com/yanghaolie/p/11110991.html
Copyright © 2011-2022 走看看