使用如下工具类可以自行构建想要的XML字符串。需要引入lombok依赖(懒得写get和set方法了)
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
具体实现如下
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XmlBuilder {
public static void main(String[] args) throws Exception {
List<Node> nodeList = new ArrayList<>();
nodeList.add(new Node("employee", null, null,List.of(new Node("department","行政处",null,null))));
System.out.println(build("xml", nodeList));
List<Node> nodeList2 = new ArrayList<>();
nodeList2.add(new Node("Parent", null, null,null));
nodeList2.add(new Node("Child1", "Child1value", null,null));
nodeList2.add(new Node("Child2", null, Arrays.asList(new Attribute("attribute1", "value1"), new Attribute("attribute2", "value2")),null));
String xmlString = build("xml", nodeList2);
System.out.println(xmlString);
}
/**
* 构造XML字符串
* @param rootElementName 根元素名
* @param nodeList 节点列表
* @return 构造的XML字符串
*/
public static String build(String rootElementName, List<Node> nodeList) throws Exception {
// 创建DocumentBuilderFactory和DocumentBuilder对象
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
// 创建新的Document对象和根元素
Document doc = dBuilder.newDocument();
Element rootElement = doc.createElement(rootElementName);
doc.appendChild(rootElement);
// 添加子节点和属性到根元素
for (Node node : nodeList) {
Element element = doc.createElement(node.getName());
element.setTextContent(node.getValue());
if (Objects.nonNull(node.getAttributeList())) {
//设置结点的属性值
for (Attribute attribute : node.getAttributeList()) {
element.setAttribute(attribute.getName(), attribute.getValue());
}
} else if (Objects.nonNull(node.getChildrenList())) {
//如果该结点有子节点,则添加子节点的值
for (Node child : node.getChildrenList()) {
Element childElement = doc.createElement(child.getName());
childElement.setTextContent(child.getValue());
//设置子结点的属性值
if (Objects.nonNull(child.getAttributeList())) {
for (Attribute attribute : child.getAttributeList()) {
childElement.setAttribute(attribute.getName(), attribute.getValue());
}
}
//添加子节点
element.appendChild(childElement);
}
}
//将结点添加到根结点下
rootElement.appendChild(element);
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
//去除XML头部声明(<?xml version="1.0" encoding="UTF-8" standalone="no"?>)
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
//启用缩进
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//指定了缩进量,可以将 "2" 替换成其他值,如 "4" 或 "tab" 等
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// 设置字符编码
transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
// 将新的Document对象转换为字符串输出
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
return writer.toString().trim();
}
/**
* 节点类
*/
@Data
@AllArgsConstructor
public static class Node {
private final String name;
private final String value;
private final List<Attribute> attributeList;
private final List<Node> childrenList;
}
/**
* 属性类
*/
@Data
@AllArgsConstructor
public static class Attribute {
private final String name;
private final String value;
}
}
测试结果(如果需要xml头部的声明,可自行去除代码的配置即可)
<xml>
<employee>
<department>行政处</department>
</employee>
</xml>
<xml>
<Parent/>
<Child1>Child1value</Child1>
<Child2 attribute1="value1" attribute2="value2"/>
</xml>
标签:XML,xml,Java,String,Node,import,字符串,new,null From: https://www.cnblogs.com/52-IT-y/p/17438217.html