树形结构转换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(网页形式展示树形结构)