java dom tree
2015 ワード
import java.io.File;
import java.io.FileWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.crimson.tree.XmlDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class MyTree {
private static String line = "--";
private static int count = 0;
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
Document doc = dbBuilder.newDocument(); // file
Element rootDirElement = null;
if (doc != null) {
File dir = new File("D:\\tree");
rootDirElement = doc.createElement(dir.getName());
// System.out.println(line+dir.getName());
indexDoc(doc, rootDirElement, dir);
doc.appendChild(rootDirElement);
// crimson-1.1.3.jar
((XmlDocument) doc).write(new FileWriter("src/result.xml"));
traver(doc.getFirstChild());
}
}
public static void traver(Node node) {
System.out.println(getLine()+node.getNodeName());
Node child = node.getFirstChild();
while (child != null) {
traver(child);
//count--;
child = child.getNextSibling();
}
count++;
}
private static void indexDoc(Document doc, Element lastElement, File dir) {
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
Element fileElement = doc.createElement(file.getName());
lastElement.appendChild(fileElement);
// System.out.println(getLine()+file.getName());
indexDoc(doc, fileElement, file);
} else {
Element fileElement = doc.createElement(file.getName());
lastElement.appendChild(fileElement);
// count--;
// System.out.println(getLine()+file.getName());
}
}
}
private static String getLine() {
String line = "";
for (int i = 0; i < count; i++) {
line = line + "--";
}
return line;
}
}