解析类:
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
3
the 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.

解决方案 »

  1.   

    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; } 

      

  2.   

    System.out.println(node.getNodeValue()); 
    这行语句是输出Node的value的。既
    the mythical man-month 
    frederick p.brooks Jr.
    1975-03-12
    the mythical man-month
    frederick p.brooks Jr. 
    null 
      

  3.   

    ~~~ getAllSubNodesName(node.getChildNodes()); 
    在你循环体里不是么。
      

  4.   

    你用到了递归处理,
    把两个System.out.println(...); 删除掉,
    在main方法中的getAllSubNodesName(nodeList)就是最后的list(含有6个元素的list结构)