javabean转xml

版权声明:注意:本文归作者所有,转载请标明原出处! 地址 : https://blog.csdn.net/qq_38366063 https://blog.csdn.net/qq_38366063/article/details/89643446

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

等等

猜你喜欢

转载自blog.csdn.net/qq_38366063/article/details/89643446