首页 > 其他分享 >JAXB实现对象与xml互转

JAXB实现对象与xml互转

时间:2023-10-18 11:01:14浏览次数:46  
标签:xml JAXBContext java JAXB JAXBException param 互转 import

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class XmlUtil {
    /**
     * JAVA对象转xml
     * @param object java对象
     * @param <T>
     * @return xml字符串
     * @throws JAXBException
     */
    public static <T> String convertXml(T object) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(object.getClass());
        // 创建 Marshaller装配器实例
        Marshaller marshaller = context.createMarshaller();
        // 可以设置的属性参见方法:com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty()
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        // 指定xml文件头
        marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 将xml写入流中
        marshaller.marshal(object, outputStream);
        // 将流转换成字符串
        return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
    }

    /**
     * xml报文转java对象
     * @param xml xml报文
     * @param clazz java对象类
     * @param <E>
     * @return java对象
     * @throws JAXBException
     */
    public static <E> E convertObject(String xml, Class<E> clazz) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(clazz);
        // 创建unmarshaller解组器实例
        Unmarshaller unmarshaller = context.createUnmarshaller();
        StringReader stringReader = new StringReader(xml);
        return (E) unmarshaller.unmarshal(stringReader);
    }

    /**
     * xml文件流转java对象
     * @param inputStream xml文件流
     * @param clazz java对象类型
     * @param <E>
     * @return java对象
     * @throws JAXBException
     */
    public static <E> E convertObject(InputStream inputStream, Class<E> clazz) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(clazz);
        // 创建unmarshaller解组器实例
        Unmarshaller unmarshaller = context.createUnmarshaller();
        return (E) unmarshaller.unmarshal(inputStream);
    }
}

 

 

 

转自:Java对象与XML报文互转 - 今夕是何年? - 博客园 (cnblogs.com)

标签:xml,JAXBContext,java,JAXB,JAXBException,param,互转,import
From: https://www.cnblogs.com/zjfjava/p/17771572.html

相关文章

  • c# RSA相关 加密 签名 PEM - XML互相转换
    安装nugetPortable.BouncyCastleusingOrg.BouncyCastle.Asn1.Pkcs;usingOrg.BouncyCastle.Asn1.X509;usingOrg.BouncyCastle.Crypto;usingOrg.BouncyCastle.Crypto.Parameters;usingOrg.BouncyCastle.Math;usingOrg.BouncyCastle.Pkcs;usingOrg.BouncyCastle.Se......
  • pom.xml 常用配置(三)
    SpringContext<!--SpringContext--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.2.RELEASE</version></dependency><dependen......
  • java.io.IOException: Could not find resource mapper/ProductCategoryMapper.xml 解
    java.io.IOException:Couldnotfindresourcemapper/ProductCategoryMapper.xml解决方案 一、问题背景通过MyBatisPlus测试达梦数据库过程中,运行测试类的时候,项目报错:“java.io.IOException:Couldnotfindresourcemapper/ProductCategoryMapper.xml”工程的目录......
  • logback-thtf.xml 日志输出控制
    <?xmlversion="1.0"encoding="UTF-8"?><configurationscan="true"scanPeriod="60seconds"debug="false"><!--日志存放路径--><propertyname="log.path"value="logs/go......
  • poi报错org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetExcepti
    场景使用poi时报错org.apache.poi.POIXMLException:java.lang.reflect.InvocationTargetException报错信息:org.apache.poi.POIXMLException:java.lang.reflect.InvocationTargetExceptionatorg.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory......
  • Mybatis xml中in的用法
    一、前端多选传字符串类型给后端,用逗号(,)分隔开后端用String类型接收该字段/***所属部门编码list*/@ApiModelProperty(name="departmentCodeList",value="所属部门编码集")privateStringdepartmentCodeList;mybatis中写法如下:<iftest="vo.departmentC......
  • 使用 Open XML SDK 实现 html 富文本转换为 docx 格式示例
     使用OpenXMLSDK实现html富文本转换为docx格式文档相对复杂。下面是一个示例。手动检测<strong>和<em>标签并应用相应的文本格式。usingSystem;usingDocumentFormat.OpenXml;usingDocumentFormat.OpenXml.Packaging;usingDocumentFormat.OpenXml.Wordproces......
  • 使用python来对字符编码序列进行互转
    排查字符集问题时,有的时候发生乱码不知道如何生成的字符,此时就需要通过字节序列来判断该字符是什么。已知utf8字节序列时,转换为unicode或者gb18030字节序列:>>>a=b'\xef\xbc\xa1'#此时a是一个bytes对象>>>b=a.decode("utf8")#此时b是一个str对象,内部是unicode的编码字......
  • 在Mac上安装lxml
    最近想开始学习一下爬虫,用来截取一些网页中的段落文字、列表、表格等信息。联想到HTML的DOM树结构,就想是不是用XPath来解析会比较合适。于是自己想从Python结合XPath的方向入手来实现网页内容解析。提到Python与XPath结合,就要用到lxml这个包了。它是一款由StefanBehnel等开发者......
  • ImportError: cannot import name 'parse_xml' from 'docx.oxml'
    问题解决:查看每一个报错的文件,比如__init__.py, composer.py找到报错的这一行,比如:fromdocx.oxmlimportparse_xml替换为:fromdocx.oxml.parserimportparse_xml注意:可能有多个文件出现这个问题,需要逐一解决!......