2

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:

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:

    /**
     * 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);
            }
        }
    }
0

1 Answer 1

5

Programming against SAX is profoundly different to programming against DOM - SAX is a push model, DOM is a pull-model. 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 is a pull-model parser API, but has many of the same advantages of the SAX approach (e.g. memory usage and performance).

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.