import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;
public class DOMDemo {
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = docBuilder.parse(new File("src/dictionary.xml"));
printXmlHeader(doc.getXmlVersion(), doc.getXmlEncoding());
printXml(doc.getDocumentElement(), 0);
}
/**
* 输出xml头
*
* @param version
* @param encode
*/
private static void printXmlHeader(String version, String encode) {
System.out.println("<?xml version=\"" + version + "\" encoding=\""
+ encode + "\">");
}
/**
* 输出xml的内容
*
* @param ele
* 为节点对象
* @param depth
* 为节点深度 .
*/
private static void printXml(Element ele, int depth) {
// 根据xml子节点的深度进行缩进
printTabWithXmlDepth(depth);
String tagName = ele.getTagName();
System.out.print("<" + tagName + ">");
// 输出该节点的子节点以及内容
if (ele.hasChildNodes()) {
NodeList nodeList = ele.getChildNodes();
System.out.println("有子节点:" + nodeList.getLength());
String word = nodeList.item(0).getNodeValue();
String explain = nodeList.item(1).getNodeValue();
System.out.println("insert into db values(" + word + " ," + explain
+ ")");
for (int index = 0; index < nodeList.getLength(); index++) {
Node node = nodeList.item(index);
// 判断该子节点是否也是一个节点
if (node.getNodeType() == Node.ELEMENT_NODE
&& node.getNodeName().equals("oneword")) {
if (node.hasChildNodes()) {
System.out.println("hahha");
if (node.hasChildNodes()) {
NodeList childlist = node.getChildNodes();
System.out.println("childchild");
if (node.getChildNodes().item(0).getNodeType() == node.ELEMENT_NODE
&& node.getChildNodes().item(1)
.getNodeType() == node.ELEMENT_NODE) {
//将xml文件读取出来组成sql语句插入数据库
System.out.println("name--------->"
+ childlist.item(0).getChildNodes()
.item(0).getNodeValue()
+ "---->"
+ childlist.item(1).getChildNodes()
.item(0).getNodeValue());
}
}
}
printXml((Element) node, depth + 1);
} else if (node.getNodeType() == Node.TEXT_NODE) {
String value = node.getNodeValue();
// DOM在获取TETX_NODE类型的节点的内容时,如果是回车(换行符),解析后的内容是由一个或多个的"\n","\t"组成的字符串,而内容(Value)节点解析后的则就是其值,不含"\n","\t"。
value = value.replaceAll("\n", "").replaceAll("\r", "")
.trim();
if (!"".equals(value)) {
printTabWithXmlDepth(depth + 1); // 由于内容需要在当前节点的情况下进行缩进
System.out.print(node.getParentNode().getNodeName()
+ "="); // 输出当前node的名字
System.out.println(">>>>:" + value);
}
}
}
}
// 收尾,如</root>
printTabWithXmlDepth(depth);
System.out.println("</" + tagName + ">");
}
/**
* 缩进
*
* @param depth
*/
private static void printTabWithXmlDepth(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("\t");
}
}
}