SAX Parser based XML Document dump
In this chapter you will learn:
Dump a XML document with SAX Parser
import java.io.StringReader;
// j a va 2 s .c om
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.XMLReader;
class MyContentHandler implements ContentHandler {
private boolean namespaceBegin = false;
private String currentNamespace;
private String currentNamespaceUri;
private Locator locator;
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
public void startDocument() {
System.out.println("<?xml version=\"1.0\"?>");
System.out.println();
}
public void endDocument() {
}
public void startPrefixMapping(String prefix, String uri) {
namespaceBegin = true;
currentNamespace = prefix;
currentNamespaceUri = uri;
}
public void endPrefixMapping(String prefix) {
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
System.out.println("<" + qName);
if (namespaceBegin) {
System.out.print(" xmlns:" + currentNamespace + "=\"" + currentNamespaceUri + "\"");
namespaceBegin = false;
}
for (int i = 0; i < atts.getLength(); i++) {
System.out.print(" " + atts.getQName(i) + "=\\" + atts.getValue(i) + "\"");
}
System.out.print(">");
}
public void endElement(String namespaceURI, String localName, String qName) {
System.out.print("</" + qName + ">");
}
public void characters(char[] ch, int start, int length) {
for (int i = start; i < start + length; i++)
System.out.print(ch[i]);
}
public void ignorableWhitespace(char[] ch, int start, int length) {
for (int i = start; i < start + length; i++)
System.out.print(ch[i]);
}
public void processingInstruction(String target, String data) {
System.out.print("<?" + target + " " + data + "?>");
}
public void skippedEntity(String name) {
System.out.print("&" + name + ";");
}
}
public class Main {
public static void main(String args[]) throws Exception {
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(new MyContentHandler());
reader.parse(is);
}
static String xmlRecords =
"<data>" +
" <employee>" +
" <name>Tom</name>"+
" <title>Manager</title>" +
" </employee>" +
" <employee>" +
" <name>Jerry</name>"+
" <title>Programmer</title>" +
" </employee>" +
"</data>";
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » XML