zoukankan      html  css  js  c++  java
  • javabean转xml

    引入pom

    <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    
    

    对应的工具类:

    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    import java.io.StringReader;
    import java.io.StringWriter;
    
    /**
     * Created by stack on 2019/4/28.
     */
    public class XmlUtil {
    
        public static Object convertXmlStrToObject(Class clazz,String xmlStr)throws Exception{
            JAXBContext context=JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller=context.createUnmarshaller();
            StringReader sr=new StringReader(xmlStr);
            return unmarshaller.unmarshal(sr);
        }
    
        /**
         *对象转换成xmlString
         *
         *createdbycaizhon2018-05-24v1.0
         */
        public static String convertToXmlStr(Object obj)throws Exception{
            //创建输出流
            StringWriter sw=new StringWriter();
    
            //利用jdk中自带的转换类实现
            JAXBContext context=JAXBContext.newInstance(obj.getClass());
    
            Marshaller marshaller=context.createMarshaller();
            //格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
            //去掉生成xml的默认报文头
            //marshaller.setProperty(Marshaller.JAXB_FRAGMENT,Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            //将对象转换成输出流形式的xml
            marshaller.marshal(obj,sw);
    
            return sw.toString();
        }
    
    }
    
    

    需要使用对应的注解

    @XmlRootElement(name = “aaa”)
    @XmlElement(name = “bbb”)

    等等

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    redis基本操作 —— hash
    redis基本操作 —— string
    redis —— linux下源码安装
    zookeeper c api 安装 & 连接 zookeeper
    wpa_supplicant移植(2.9版本)
    hostapd移植(2.6版本为例)
    hostapd移植(2.7版本)
    使用MKdocs搭建个人主页并关联到GithubPages上
    yolov5的yaml文件解析
    RANSAC——(RANdom SAmple Consensus(随机抽样一致))
  • 原文地址:https://www.cnblogs.com/javayida/p/13347006.html
Copyright © 2011-2022 走看看