侧边栏壁纸
博主头像
lai博主等级

  • 累计撰写 51 篇文章
  • 累计创建 19 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

将JavaBean转换为XML工具类

lai
lai
2023-06-22 / 2 评论 / 0 点赞 / 584 阅读 / 1,112 字
温馨提示:
本文最后更新于 2023-11-22,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

简介

该工具类专注于提供JavaBean对象到XML格式的转换功能。通过使用该工具,可以方便地将JavaBean对象中的属性和数据转换成对应的XML格式,实现数据的序列化和持久化。

此工具类使得将JavaBean对象转换为XML格式变得简单高效。它通过遍历JavaBean对象的属性,将其映射到XML文档的元素中,并为每个属性创建对应的XML标签,最终生成符合XML规范的文档结构。

通过提供易于使用的方法和选项,该工具类可以灵活地适应不同类型和结构的JavaBean对象,将其转换为可读性强、易于解析和处理的XML格式,为数据交换和持久化提供了便利。


import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

/**
 * @author 
 * @date 2023年6月20日 下午5:03:00
 * @Description Jaxb工具类 xml和java类相互转换
 */
public class JaxbXmlUtil {
	public static final String DEFAULT_ENCODING = "UTF-8";

	/**
	 * pojo转换成xml 默认编码UTF-8
	 *
	 * @param obj
	 *            待转化的对象
	 * @return xml格式字符串
	 * @throws Exception
	 *             JAXBException
	 */
	public static String convertToXml(Object obj) throws Exception {
		return convertToXml(obj, DEFAULT_ENCODING);
	}

	/**
	 * pojo转换成xml
	 *
	 * @param obj
	 *            待转化的对象
	 * @param encoding
	 *            编码
	 * @return xml格式字符串
	 * @throws Exception
	 *             JAXBException
	 */
	public static String convertToXml(Object obj, String encoding) throws Exception {
		String result = null;

		JAXBContext context = JAXBContext.newInstance(obj.getClass());
		Marshaller marshaller = context.createMarshaller();
		// 指定是否使用换行和缩排对已编组 XML 数据进行格式化的属性名称。
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
		marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
		marshaller.setListener(new MarshallerListener());
		StringWriter writer = new StringWriter();
		marshaller.marshal(obj, writer);
		result = writer.toString();

		return result;
	}
	
	/**
     * xml转换成JavaBean
     *
     * @param xml xml格式字符串
     * @param t 待转化的对象
     * @return 转化后的对象
     * @throws Exception JAXBException
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertToJavaBean(String xml, Class<T> t) throws Exception {

		JAXBContext jaxbContext = JAXBContext.newInstance(t);
		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		StringReader reader = new StringReader(xml);

		SAXParserFactory sax = SAXParserFactory.newInstance();
		sax.setNamespaceAware(false);
		XMLReader xmlReader = sax.newSAXParser().getXMLReader();

		Source source = new SAXSource(xmlReader, new InputSource(reader));
		Object o = unmarshaller.unmarshal(source);
		return (T) o;
	}

}

/**
 * @author 
 * @date 2021年11月10日 上午10:01:32
 * @Description
 */
public class MarshallerListener extends Listener {
    public static final String BLANK_CHAR = "";

    @Override
    public void beforeMarshal(Object source) {
        super.beforeMarshal(source);
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                if (f.getType() == String.class && f.get(source) == null) {
                    f.set(source, BLANK_CHAR);
				} else if (f.getType() == BigDecimal.class && f.get(source) == null) {
					f.set(source, BigDecimal.ZERO);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}

编写java实体类

XmlRootElement 指定ROOT(顶级)标签名
XmlType-propOrder指定内部标签排序
XmlAttribute 设置标签属性
XmlElement 设置子标签元素

Soap ROOT标签示例

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "header", "body" })
@XmlRootElement(name = "soapenv:Envelope")
public class SoapRequestBO {
	@XmlAttribute(name = "xmlns:soapenv")
	protected String soapenv = "http://schemas.xmlsoap.org/soap/envelope/";


	@XmlElement(required = true, name = "soapenv:Header")
	protected String header;

	@XmlElement(required = true, name = "soapenv:Body")
	protected SoapRequestBodyBO body;

	/**
	 * @return the soapenv
	 */
	public String getSoapenv() {
		return soapenv;
	}

	/**
	 * @param soapenv
	 *            the soapenv to set
	 */
	public void setSoapenv(String soapenv) {
		this.soapenv = soapenv;
	}


	public SoapRequestBodyBO getBody() {
		return body;
	}

	public void setBody(SoapRequestBodyBO body) {
		this.body = body;
	}

	/**
	 * @return the header
	 */
	public String getHeader() {
		return header;
	}

	/**
	 * @param header
	 *            the header to set
	 */
	public void setHeader(String header) {
		this.header = header;
	}

}

Soap Body标签示例

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "soapenv:Body")
public class SoapRequestBodyBO {

	@XmlElement(required = true, name = "main:sendRecv")
	public String paramJson;


    public String getParamJson() {
        return paramJson;
    }

    public void setParamJson(String paramJson) {
        this.paramJson = paramJson;
    }

}

验证

public class Main {
    public static void main(String[] args) throws Exception {
        SoapRequestBO soapRequestBO = new SoapRequestBO();
        String header =  "header content";
        SoapRequestBodyBO soapRequestBodyBO = new SoapRequestBodyBO();
        Map<String, String> jsonMap = new HashMap<>();
        jsonMap.put("name","用户名");
        jsonMap.put("age", "22");
        soapRequestBodyBO.setParamJson(JSON.toJSONString(jsonMap));
        soapRequestBO.setHeader(header);
        soapRequestBO.setBody(soapRequestBodyBO);
        System.out.println(JaxbXmlUtil.convertToXml(soapRequestBO));
    }
}

通过上述方法可以得到一个soap格式的报文,这样可以使用通过http请求调用webservice接口,反过来也可以解析xml格式报文

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
	<soapenv:Header>header content</soapenv:Header>
	<soapenv:Body><main:sendRecv>{"name":"用户名","age":"22"}</main:sendRecv>
	</soapenv:Body>
</soapenv:Envelope>

完整案例

案例使用了jdk17 javax已修改为jakarta
https://github.com/SevenBigBee/spring-boot3.0.0-demo/tree/master/bean2xml

0

评论区