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”)

    等等

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    protobuf 协议 windows 下 C++ 环境搭建
    protobuf 协议 windows 下 java 环境搭建
    ProtocolBuffers (二) android与PC,C#与Java 利用protobuf 进行无障碍通讯【Socket】
    C++ ofstream和ifstream详细用法
    C# 关于out和ref的问题
    java 解析office文件 大全
    Ezhuang
    IOS
    Android Client and PHP Server
    一个IM开源项目LiteTalk
  • 原文地址:https://www.cnblogs.com/javayida/p/13347006.html
Copyright © 2011-2022 走看看