简体   繁体   English

如何从使用Dom解析转换为使用SAX解析

[英]How to convert from parsing with Dom to parsing with SAX

I'm parsing an XML document into my own structure using DOM, but in another question I was advised to use SAX, how would I convert the following: 我正在使用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;
}

Here is my DomTree constructor: 这是我的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);
            }
        }
    }

Programming against SAX is profoundly different to programming against DOM - SAX is a push model, DOM is a pull-model. 针对SAX进行编程与针对DOM进行编程有很大不同-SAX是推送模型,DOM是拉模型。 Converting your code from one to the other is a very non-trivial task. 将您的代码从一个转换为另一个是不平凡的任务。

Given your situation, I would recommend using STAX rather than SAX. 根据您的情况,我建议您使用STAX而不是SAX。 STAX is a pull-model parser API, but has many of the same advantages of the SAX approach (eg memory usage and performance). STAX是拉模型解析器API,但具有SAX方法的许多相同优点(例如,内存使用和性能)。

STAX comes with Java 6, but if you want to use it with Java 5 you need to download a STAX processor (eg Woodstox ). STAX随Java 6一起提供,但如果要与Java 5一起使用,则需要下载STAX处理器(例如Woodstox )。 The Woodstox site has plenty of examples for you to look at. Woodstox网站上有许多示例供您查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM