樹形結構轉換xml總結
這幾天碰見個問題,需要将庫裡的樹形結構存儲資料轉換為xml形式,進而可以利用XMind進行檢視。類似這種結構:
0 -1 父節點
101 0 節點1
102 0 節點2
2101001 101 節點4
一、基本思路
從庫裡導出資料存入檔案中,也可以直接從庫中讀取資料。
二、實作步驟
1、定義節點類型:
import java.util.List;
public class Node {
private String id; //節點id
private String parentId; //父節點id
private String Text; //節點名稱
private List<Node> children; //子節點
public Node(String id, String parentId, String Text) {
super();
this.id = id;
this.parentId = parentId;
this.Text = Text;
}
public Node(String id, String Text, Node parent) {
super();
this.id = id;
this.Text = Text;
this.parentId = parent.getId();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getText() {
return Text;
}
public void setText(String Text) {
this.Text = Text;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
}
2、将list類型裝換成樹形結構
findById、和 findByPid 分别為通過id 查找節點, 和通過節點查找子節點。
public List<Node> getTree() {
List<Node> root = findById("0"); //get root node
return buildTreeMulti(root);
}
private List<Node> buildTreeMulti(List<Node> root) {
for(int i=0; i < root.size(); i++) {
List<Node> children = findByPid(root.get(i).getId());
buildTreeMulti(children);
root.get(i).setChildren(children);
}
return root;
}
3、将樹形結構寫入XML
private static void writetoXML(List<Node> treeroot, String outfile) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
doc.setXmlStandalone(true);
Element root = doc.createElement("map");
root.setAttribute("version", "0.8.1");
doc.appendChild(root);
doc = buildXML(treeroot, doc, root);
writeXml(doc, outfile);
}
private static Document buildXML(List<Node> nodes, Document doc, Element faEle) {
for(int i=0; i < nodes.size(); i++) {
Element fa = doc.createElement("node");
fa.setAttribute("TEXT", nodes.get(i).getText());
faEle.appendChild(fa);
List<Node> childtrees = nodes.get(i).getChildren();
doc = buildXML(childtrees, doc, fa);
}
return doc;
}
public static void writeXml(Document document, String outfile) throws Exception{
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(outfile);
transformer.transform(source, result);
}
三、擴充
相應的也可以把xml中的資料裝換到Excel中等。
參考博文:https://blog.csdn.net/u012116457/article/details/45912887(網頁形式展示樹形結構)