Java 如何从Dom解析转换为SAX解析

Java 如何从Dom解析转换为SAX解析,java,xml,dom,parsing,sax,Java,Xml,Dom,Parsing,Sax,我正在使用DOM将XML文档解析为我自己的结构,但在另一个例子中,有人建议我使用SAX,我如何转换以下内容: public static DomTree<String> createTreeInstance(String path) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory docBuilderFactory = DocumentBuil

我正在使用DOM将XML文档解析为我自己的结构,但在另一个例子中,有人建议我使用SAX,我如何转换以下内容:

public static DomTree<String> createTreeInstance(String path) 
  throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = docBuilderFactory.newDocumentBuilder();
    File f = new File(path);
    Document doc = db.parse(f);       
    Node node = doc.getDocumentElement(); 
    DomTree<String> tree = new DomTree<String>(node);
    return tree;
}
公共静态域树createTreeInstance(字符串路径)
抛出ParserConfiguration异常、SAXException、IOException{
DocumentBuilderFactory docBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder db=docBuilderFactory.newDocumentBuilder();
文件f=新文件(路径);
文档doc=db.parse(f);
Node=doc.getDocumentElement();
DomTree-tree=新的DomTree(节点);
回归树;
}
这是我的DomTree构造函数:

    /**
     * Recursively builds a tree structure from a DOM object.
     * @param root
     */
    public DomTree(Node root){      
        node = root;        
        NodeList children = root.getChildNodes();
        DomTree<String> child = null;
        for(int i = 0; i < children.getLength(); i++){  
            child = new DomTree<String>(children.item(i));
            if (children.item(i).getNodeType() != Node.TEXT_NODE){
                super.children.add(child);
            }
        }
    }
/**
*递归地从DOM对象构建树结构。
*@param根
*/
公共域树(节点根){
节点=根;
NodeList childrends=root.getChildNodes();
DomTree-child=null;
对于(inti=0;i
针对SAX的编程与针对DOM的编程有着深刻的不同——SAX是一种推式模型,DOM是一种拉式模型。将代码从一个转换到另一个是一项非常重要的任务

考虑到您的情况,我建议使用STAX而不是SAX。STAX是一个拉模型解析器API,但具有许多与SAX方法相同的优点(例如内存使用和性能)

STAX随Java 6一起提供,但如果您想将其与Java 5一起使用,则需要下载一个STAX处理器(例如)。Woodstox站点有很多例子供您参考