JAVA将list转化为xml文件

时间:2022-09-20 05:08:17

pojo类:

 public class TreeNode {
private int id;
private String nodeId;
private String parentId;
private String hrefAddress;
private String nodeName; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getNodeId() {
return nodeId;
} public void setNodeId(String nodeId) {
this.nodeId = nodeId;
} public String getParentId() {
return parentId;
} public void setParentId(String parentId) {
this.parentId = parentId;
} public String getHrefAddress() {
return hrefAddress;
} public void setHrefAddress(String hrefAddress) {
this.hrefAddress = hrefAddress;
} public String getNodeName() {
return nodeName;
} public void setNodeName(String nodeName) {
this.nodeName = nodeName;
} }

将list转化为xml形式的字符串的工具类:

 public class TreeUtil {
/**
* 根据节点数据集合,生成XML
* @param treeNodes 权节点集合
* @return
*/
public String parseNodeToXML(List<TreeNode> treeNodes) {
StringBuffer xmlnodes = new StringBuffer();
if (treeNodes != null && treeNodes.size() > 0) {
xmlnodes.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
xmlnodes.append("<nodes>");
for (int i = 0; i < treeNodes.size(); i++) {
TreeNode node = treeNodes.get(i);
xmlnodes.append("<node nodeId='" + node.getNodeId() + "' parentId='" + node.getParentId()
+ "' hrefAddress='" + node.getHrefAddress() + "'>" + node.getNodeName() + "</node>");
}
xmlnodes.append("</nodes>");
} return xmlnodes.toString();
}
}

将字符串写入到文件中:

 public static void main(String[] args) throws Exception {
List<TreeNode> list = new ArrayList<TreeNode>(); for (int i = 0; i < 5; i++) {
TreeNode treeNode = new TreeNode();
treeNode.setHrefAddress("hrefAddress" + i);
treeNode.setId(i);
treeNode.setNodeId("nodeId" + i);
treeNode.setNodeName("nodeName" + i);
treeNode.setParentId("parentId" + i);
list.add(treeNode);
} String xmlFile = new TreeUtil().parseNodeToXML(list); FileWriter writer = new FileWriter("F:/node.xml"); writer.write(xmlFile);
writer.flush();
writer.close();
System.out.println("写入完成!");
}