DOM解析XML

yangcuiyu發表於2008-09-09
解析類:
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.

相關文章