2 Attachment(s)
SAX Parsing And Keeping Track Of Children
Hi,
I'm trying to parse a document using SAX for Java. I need to keep track of the parent of the children in an XML format that allows for infinite decendants. I need to keep track of the parent as I go through. When I find the root phase object, I need to create an object in the database, retrieve the ID of the stored object. When I get to the children I need to know who their parent is so I can set their parentID in the database. How do I keep track of the parent? I included an XML file and a diagram showing the hierarchy. If I go all the way down to B_level4, how do I know that B_level2 is the child of A_level1 and not A_level3?
I was going to:
- find the first phase and set it to current
- Get the level below, set current to parent, and set the id to the current
How do I deal with the infinite depth (having phases within phases) and keeping track of who the parent is?
Thanks,
Stan
Re: SAX Parsing And Keeping Track Of Children
Use a stack - when startElement is called, push a new element on the stack, when endElement is called, pop the stack.
Attached is some code (incomplete) which SAX parses XML into a Document. (Before anyone asks - so a massive XML document can be processed througn an XSLT in chunks). It uses a stack to keep track of parent elements. I suspect this could easily be adapted to keep track of your database IDs.
Code:
import java.util.Stack;
public class MySaxHandler extends DefaultHandler {
// These are all initialised by the constructor (omitted)
private Document doc = null;
private Element workingElement = null;
private Stack workingStack = null;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// Add element to the document ....
Element temp = doc.createElement(qName);
workingElement.appendChild(temp);
// Push the current working element on the stack ...
workingStack.push(workingElement);
// And make the current element the working one
workingElement = temp;
}
public void endElement(String uri, String localName, String qName) throws SAXException {
// Pop off the stack ....
workingElement = (Element)workingStack.pop();
}
public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
String chars = new String(arg0, arg1, arg2).toUpperCase();
Text t = doc.createTextNode(chars);
workingElement.appendChild(t);
}
}