DOM解析XML

08-09-09 yangcuiyu
解析类:
package tt;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TestURL {

/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
static ArrayList list = new ArrayList();
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
// TODO Auto-generated method stub
String abc="abc.xml";
URL url = TestURL.class.getClassLoader().getResource(abc);
String filePath = url.getPath();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(filePath));
Element element = doc.getDocumentElement();
NodeList nodeList = element.getChildNodes();
System.out.println(getAllSubNodesName(nodeList));

}
public static List getAllSubNodesName(NodeList nodeList){


for(int i=0;i <nodeList.getLength();i++){
Node node = nodeList.item(i);
if(node.getChildNodes().getLength() <1){
System.out.println(node.getNodeValue());
list.add(node.getNodeValue());
}
getAllSubNodesName(node.getChildNodes());
}
System.out.println(list.size());
return list;

}
}

xml格式:
<?xml version="1.0" encoding="UTF-8"?>
<all> <book> <title>the mythical man-month </title> <writer>frederick p.brooks Jr. </writer> <publishdate>1975-03-12 </publishdate> </book> <book> <title>the mythical man-month </title> <writer>frederick p.brooks Jr. </writer> <publishdate/> </book> </all>


输出结果:
the mythical man-month
1
1
frederick p.brooks Jr.
2
2
1975-03-12
3
3
3the mythical man-month
4
4
frederick p.brooks Jr.
5
5
null
6
6
6

[the mythical man-month, frederick p.brooks Jr., 1975-03-12, the mythical man-month, frederick p.brooks Jr., null]


为什么输入数字那么多次?为什么不应该是一次6.

freebox
2008-09-10 20:54
因为有方法递归调用。

yangcuiyu
2008-09-11 10:24
是啊!递归调用是在输出之前,我想不应该输出数字就进入下次递归了吧?

banq
2008-09-11 10:41
你自己设个断点调试,跟踪不就行了,有关设计方面问题多多提问。

猜你喜欢