使用Marshaller 将Java对象转化为XML格式
-
对象转xml内容
①工具类public static String convertObjectToXml(Object obj) throws Exception { StringWriter writer = new StringWriter(); // 创建 JAXBContext 和 Marshaller JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); // 设置 Marshaller 属性 // 指定是否使用换行和缩排对已编组 XML 数据进行格式化的属性名称 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 指定是否带有xml报文头 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 将 Java 对象转换成 XML 标签 marshaller.marshal(obj, writer); return writer.toString(); }
②嵌套对象
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * Created with IntelliJ IDEA. * * @Author: Administrator * @Date: 2023/04/17/13:32 * @Description: */ @XmlRootElement(name = "WinResponse") @XmlAccessorType(XmlAccessType.FIELD) public class WinResponse { private RowItem rowItem; public WinResponse() { } public WinResponse(RowItem rowItem) { this.rowItem = rowItem; } public RowItem getRowItem() { return rowItem; } public void setRowItem(RowItem rowItem) { this.rowItem = rowItem; } }
import javax.xml.bind.annotation.XmlRootElement; /** * Created with IntelliJ IDEA. * * @Author: Administrator * @Date: 2023/04/17/13:32 * @Description: */ @XmlRootElement public class RowItem { private String brlb; private String codetype; private String code; public RowItem() { } public RowItem(String brlb, String codetype, String code) { this.brlb = brlb; this.codetype = codetype; this.code = code; } public String getBrlb() { return brlb; } public void setBrlb(String brlb) { this.brlb = brlb; } public String getCodetype() { return codetype; } public void setCodetype(String codetype) { this.codetype = codetype; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
③效果图
- 字符串转xml标签
/** * * @param value 标签内的值 * @param xml 标签名称 * @return * @throws Exception */ public static String convertStringToXml(String value, String xml) throws Exception { // 创建一个新的 XML 文档 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); // 创建根元素 Element rootElement = doc.createElement(xml); doc.appendChild(rootElement); // 创建子元素并设置文本内容 rootElement.setTextContent(value); // 将 XML 文档转换为字符串 TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString(); }