No man's knowledge here can go beyond his experienceJohn Locke
Relates to Web Standards and Java
Recently been testing the main XML parsing methods in Java a bit, giving me the chance to play around in Eclipse and broaden my Java and XML knowledge. Previously I have only really used the DOM parser in the Apache Xerces package, since this equates well to similar Javascript DOM coding for HTML documents.
While the DOM is an excellent choice for document manipulation, the event driven nature of SAX makes it an excellent choice for extracting particular information from a document.
This very simple code snippet shows the contents of a Class extending org.xml.sax.helpers.DefaultHandler to display the
level of nesting in an XML (or HTML) document, by utilising the Stack data structure.
private java.util.Stack stack = new java.util.Stack();
[.. snip ..]
public void startElement(
String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
if (stack.size() > 0)
{
short temp = (short)stack.size();
while (temp– > 0)
{
System.out.print("t");
}
}
System.out.println(localName);
stack.add(localName);
}
public void endElement(
String namespaceURI,
String localName,
String qName)
throws SAXException {
stack.pop();
}
JDOM also offers some interesting classes for XML
parsing with a more Java-centric approach. In particular the contributed
ResultSetBuilder Class in the org.jdom.contrib.input package offers a very concise API for
converting SQL data into an XML document.:
s = conn.createStatement();
rs = s.executeQuery(query);
ResultSetBuilder builder =
new ResultSetBuilder(rs,
"library", "book",
Namespace.getNamespace(namespace));
builder.setAsAttribute("isbn");
builder.setAsAttribute("format");
Document doc = builder.build();
XMLOutputter outp =
new XMLOutputter(" ", true);
outp.setTrimAllWhite(true);
outp.output(doc,
new FileOutputStream(fileID));
Posted on Saturday, Nov 08, 2003 at 03:19:49.
Comments on XML Parsing Snippets (0)