pojo类:
1 public class TreeNode { 2 private int id; 3 private String nodeId; 4 private String parentId; 5 private String hrefAddress; 6 private String nodeName; 7 8 public int getId() { 9 return id; 10 } 11 12 public void setId(int id) { 13 this.id = id; 14 } 15 16 public String getNodeId() { 17 return nodeId; 18 } 19 20 public void setNodeId(String nodeId) { 21 this.nodeId = nodeId; 22 } 23 24 public String getParentId() { 25 return parentId; 26 } 27 28 public void setParentId(String parentId) { 29 this.parentId = parentId; 30 } 31 32 public String getHrefAddress() { 33 return hrefAddress; 34 } 35 36 public void setHrefAddress(String hrefAddress) { 37 this.hrefAddress = hrefAddress; 38 } 39 40 public String getNodeName() { 41 return nodeName; 42 } 43 44 public void setNodeName(String nodeName) { 45 this.nodeName = nodeName; 46 } 47 48 }
将list转化为xml形式的字符串的工具类:
1 public class TreeUtil { 2 /** 3 * 根据节点数据集合,生成XML 4 * @param treeNodes 权节点集合 5 * @return 6 */ 7 public String parseNodeToXML(List<TreeNode> treeNodes) { 8 StringBuffer xmlnodes = new StringBuffer(); 9 if (treeNodes != null && treeNodes.size() > 0) { 10 xmlnodes.append("<?xml version="1.0" encoding="UTF-8"?>"); 11 xmlnodes.append("<nodes>"); 12 for (int i = 0; i < treeNodes.size(); i++) { 13 TreeNode node = treeNodes.get(i); 14 xmlnodes.append("<node nodeId='" + node.getNodeId() + "' parentId='" + node.getParentId() 15 + "' hrefAddress='" + node.getHrefAddress() + "'>" + node.getNodeName() + "</node>"); 16 } 17 xmlnodes.append("</nodes>"); 18 } 19 20 return xmlnodes.toString(); 21 } 22 }
将字符串写入到文件中:
1 public static void main(String[] args) throws Exception { 2 List<TreeNode> list = new ArrayList<TreeNode>(); 3 4 for (int i = 0; i < 5; i++) { 5 TreeNode treeNode = new TreeNode(); 6 treeNode.setHrefAddress("hrefAddress" + i); 7 treeNode.setId(i); 8 treeNode.setNodeId("nodeId" + i); 9 treeNode.setNodeName("nodeName" + i); 10 treeNode.setParentId("parentId" + i); 11 list.add(treeNode); 12 } 13 14 String xmlFile = new TreeUtil().parseNodeToXML(list); 15 16 FileWriter writer = new FileWriter("F:/node.xml"); 17 18 writer.write(xmlFile); 19 writer.flush(); 20 writer.close(); 21 System.out.println("写入完成!"); 22 }