How to parse the XML file using SAXParser and convert it to Nodelists using Java


I am new to SAXParser, so please forgive me.

How can I parse any XML file and convert it to List<XNode>? Below is the structure of class XNode:

class XNode{

    private String nodeName;
    private String nodeValue;
    private List<XAttribute> attributes;
    private boolean isParentNode;
    private List<XNode> childNodes;

Also the structure of XAttribute:

class XAttribute{

    private String name;
    private String value;

By parsing any file, it should return the List objects.

So far, I have tried below code but don't know, how to check and attach childNodes.

public class XmlProcesser extends DefaultHandler {
    XMLResponse xmlResponse = null;
    boolean endtag = false;

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        System.out.print("" + qName + "");
        if (attributes.getLength() == 0) {
        } else {
            for (int index = 0; index < attributes.getLength(); index++) {
                System.out.print(attributes.getLocalName(index) + " =  " + attributes.getValue(index));

    public void characters(char ch[], int start, int length) throws SAXException {
        String s = new String(ch, start, length);
        endtag = false;

    public void endElement(String uri, String localName,
            String qName) throws SAXException {
        endtag = true;
        System.out.print("  " + qName + "  ");


One usual way to do this is by using a Stack and a notion of current node. When you encounter a startElement you do the following

  1. Create a new element child
  2. Add this child element to the current element
  3. Push the current element on the stack
  4. Make the child element the new current element.

When you encounter endElement you do the reverse:

  1. Pop the top element from the stack and make the current element again.

The bottom of the stack is the root.