读取XML文件
所用类
javax.xml.parsers.DocumentBuilderFactory;
javax.xml.parsers.DocumentBuilder;
org.w3c.dom.Document;
org.w3c.dom.Element;
org.w3c.dom.NodeList;
org.w3c.dom.node
nodeList,Element实现node结点,并不是所有实现node接口的都是结点,其他包括许多空结点,如Test结点就没有了结点,其nodeName 用#text代替,nodeValue为null,attributes为null
默认一个换行就一个结点
如文件
<st>
<a>a</a>
<b>b</b>
</st>
就认为是五个结点分别是 #test a #test b #test这五个结点
读取XML文件
/**
* 读取xml文件
* @param file xml文件名
* @param list 为null,用于内部引用
* @param table 存储数据的hashtable
*/
public static void recursion(String file,NodeList list,Hashtable table){
if(file!=null){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
list = document.getChildNodes();
} catch (Exception e) {
// TODO: handle exception
}
}
for(int i = 0; i<list.getLength(); i++){
if(list.item(i).getChildNodes().getLength()>=1){
ReadXML.recursion(null, list.item(i).getChildNodes(),table);
}
}
if(list.item(0).hasChildNodes()==false&&list.getLength()==1){
table.put(list.item(0).getParentNode().getNodeName(), list.item(0).getNodeValue());
}
}