2

我正在使用 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;
}

这是我的 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);
            }
        }
    }
4

1 回答 1

4

针对 SAX 的编程与针对 DOM 的编程有很大的不同——SAX 是推模型,DOM 是拉模型。将您的代码从一个转换到另一个是一项非常重要的任务。

鉴于您的情况,我建议使用 STAX 而不是 SAX。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 (e.g. Woodstox). The Woodstox site has plenty of examples for you to look at.

于 2009-07-16T13:18:17.497 回答