package Dom;import java.io.File;
import java.io.IOException;
import java.util.Vector;import org.w3c.dom.Node;
import org.w3c.dom.Document;
//import org.w3c.dom.Element;
//import org.w3c.dom.NamedNodeMap;
//import org.w3c.dom.Node;
import org.w3c.dom.NodeList;import javax.xml.parsers.DocumentBuilder;   
import javax.xml.parsers.DocumentBuilderFactory;   
import javax.xml.parsers.ParserConfigurationException;   
import org.xml.sax.SAXException;
public class getnodes { /**
 * @param args
 */
public static Node DocNode;//文档作为一个最高节点
public static Node HeadNode;//其次文档中的一级子结点
public static Vector<String>ChildNodes;//文档中的三级子节点集
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.parse(new File("MyPage.xml"));
GetNode(document);
ShowNodes();
}catch(SAXException se){
Exception e=se;//解析过程错误
if(se.getException()==null)
e=se.getException();
e.printStackTrace();
}catch(ParserConfigurationException pe)
{//错误设定
pe.printStackTrace();
}
}
public static void GetNode(Node node){
NodeList child= node.getChildNodes();//寻找下一级的子结点
int length = child.getLength();
for(int i=0; i<length; i++)
{
Node anode= child.item(i);
if(anode.hasChildNodes())
GetNode(anode);
else
{
int childlength = ChildNodes.size();
    boolean k=true;
for(int j=0; j<childlength; j++)
if(anode.getNodeName()==ChildNodes.elementAt(j))
k=false;
    if(k)
     ChildNodes.addElement(anode.getNodeName());
}
}
}public static void ShowNodes()
{
System.out.println("文本中最大的子结点集合:");
int length = ChildNodes.size();
for(int i=0; i<length; i++)
System.out.println(ChildNodes.elementAt(i));
}}

解决方案 »

  1.   

     <bookstore>
    - <book >
      <title lang="en">Harry Potter</title> 
      <author>J K. Rowling</author> 
      <year>2005</year> 
      <price>29.99</price> 
      </book>
    - <book>
      <title lang="en">Everyday Italian</title> 
      <author>Giada De Laurentiis</author> 
      <year>2005</year> 
      <price>30.00</price> 
      </book>
    - <book>
      <title lang="en">Learning XML</title> 
      <author>Erik T. Ray</author> 
      <year>2003</year> 
      <price>39.95</price> 
      </book>
    - <book>
      <title lang="en">XQuery Kick Start</title> 
      <author>James McGovern</author> 
      <author>Per Bothner</author> 
      <author>Kurt Cagle</author> 
      <author>James Linn</author> 
      <author>Vaidyanathan Nagarajan</author> 
      <year>2003</year> 
      <price>49.99</price> 
      </book>
    - <test>
      <time>2011/7/20</time>
      <name>spring</name>
      <tel value="MyOwne">15454544541</tel>
      </test>
      </bookstore>
    这是我用的例子