binary.xml:<a>
  <b>
    <c>C</c>
    <d>D</d>
  </b>
  <e>
    <f>F</f>
    <g>G</g>
  </e>
</a>CountSubElts.java代码:import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;public class CountSubElts {  // a variable for each component
  protected DomSearch domSearch;
  protected Dom2Sax dom2Sax;
  protected CountSax countSax;  /* the constructor instantiates the components and wires them together */
  public CountSubElts() {
    domSearch = 
      new DomSearch();         // obeys commands, reads files into DOM trees
    dom2Sax = new Dom2Sax();   // takes us from DOM to SAX
    domSearch.setSaxOutput(dom2Sax);          // connect DomSearch to Dom2Sax
    domSearch.initFromDict(new PropDict());   // start with defaults    countSax = new CountSax();   // takes us from SAX to output
    dom2Sax.setHandlerBase(countSax);   // connect Dom2Sax to CountSax
  }  // pass all commands and definitions into the start of the pipe:  public String doCommand(String cmd) {
    return domSearch.doCommand(cmd);
  } 
  public void setDef(String name, String val) {    // calls setDef() of DomSeach that calls setDef() of its PropDict
    // We use it below to set fileName in DomSearch
    domSearch.setDef(name, val);
  }   // "traverse" uses the successor method of DomSearch
  // to do a preorder examination of all subtrees of current node.
  // We call writeNode() on each, sending the subtree to Dom2Sax
  // which sends it to CountSax.
  public void traverse() throws Exception {
    Node startNode = domSearch.getNode();
    Node currentNode = domSearch.successor(startNode);
    while (startNode != currentNode) {
      System.out.print(currentNode.getNodeName() + " ");
      domSearch.writeNode(currentNode);
      currentNode = domSearch.successor(currentNode);
    } 
  }   public static void main(String[] argv) throws Exception {
    CountSubElts countSubElts = new CountSubElts();    // set fileName in DomSearch
    countSubElts.setDef("fileName", argv[0]);    // call doCommand() of DomSearch; the file gets parsed into DOM tree
    String err = countSubElts.doCommand("initFile");    countSubElts.traverse();
  } 
}

解决方案 »

  1.   

    谢谢一楼的,不过我的意思是只用SAX  :)
      

  2.   

    试试JDOM吧,非常的简单,看看它的SAMPLE你就知道怎么用了
      

  3.   

    public void characters(char[] ch, int start, int length) throws
            SAXException
        {        String s = new String(ch, start, length);
            if(!s.startsWith("\n") && !"".equals(s.trim()))
            {
               System.out.println(s);//s is what you needed
            }    }