【问题标题】:How to convert from parsing with Dom to parsing with SAX如何从使用 Dom 解析转换为使用 SAX 解析
【发布时间】:2009-07-16 13:08:13
【问题描述】:

我正在使用 DOM 将 XML 文档解析为我自己的结构,但在另一个 question 中,有人建议我使用 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);
            }
        }
    }

【问题讨论】:

    标签: java xml dom parsing sax


    【解决方案1】:

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

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

    STAX 随 Java 6 一起提供,但如果你想在 Java 5 中使用它,你需要下载一个 STAX 处理器(例如Woodstox)。 Woodstox 网站有大量示例供您查看。

    【讨论】:

      猜你喜欢
      • 2011-06-17
      • 2015-10-08
      • 2020-01-17
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      相关资源
      最近更新 更多