if by document XML you meant a DOM parser, this answer will be useless, as this is an implementation of a SAX parser. DOM parsing is relatively simple if you look through the API so theres no point explaining that.
The approach i take when parsing with SAX is to have two class String vars named parentElement and currentElement. When the start element event is fired, add the element to a stack and make a deep copy of any attributes as the attribute object will be reused by the parser and hence your attributes will be lost. I usually chuck attrs in a mapping with element name as the key. set the currentElement var to the element name of the start element method.
Now when the characters event is fired, assign the value of the second top stack element to parentElement then perform a test similar to the following:
if( parentElement.equals("root") )
if( currentElement.equals("data")
//handle 1 and 2
if you want to handle 1 and 2 differently, you will need to put them into different elements.
Does this make any sense whatsoever?
Using JAXP:
String str = "<root><data>1</data><data>2</data></root>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(str.getBytes()));
import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class PrettyPrinter {
public static void main(String[] args) {
// Assume filename argument
String filename = args[0];
try {
// Build the document with SAX and Xerces, no validation
SAXBuilder builder = new SAXBuilder();
// Create the document
Document doc = builder.build(new File(filename));
// Output the document, use standard formatter
XMLOutputter fmt = new XMLOutputter();
fmt.output(doc, System.out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The above code is taken directly from
http://www.javaworld.com/javaworld/jw-05-2000/jw-0518-jdom-p2.html
u don't have to use Factories, this is what is said in that excerpt, it is very easy to use, and it is said that 80 % of the xml work can be done with 20 % or less work using JDOM.
n joy ....
</ksenji>