2009年1月3日

XML Parsing With SAX


import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Stack;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Main extends DefaultHandler {

private Stack<String> stack;
private Stack<String> tempStack;
private PrintWriter writer;

private String getPath() {
StringBuilder sb = new StringBuilder();
Iterator<String> iter = stack.iterator();
while (iter.hasNext()) {
String tag = (String) iter.next();
sb.append('/').append(tag);
}
return sb.toString();
}

public void startDocument ()
throws SAXException
{
stack = new Stack<String>();
tempStack = new Stack<String>();
writer = new PrintWriter(System.out);
}

public void endDocument ()
throws SAXException
{
stack = null;
tempStack = null;
writer.close();
writer = null;
}

public void startElement (String uri, String localName,
String qName, Attributes attributes)
throws SAXException
{
stack.push(qName);
writer.println("tag: " + getPath());
for ( int i = 0; i < attributes.getLength(); i++ ) {
writer.println(" attribute: " + attributes.getQName(i)
+ "\tvalue: " + attributes.getValue(i));
}

}

public void endElement (String uri, String localName, String qName)
throws SAXException
{
String name = stack.pop();
while(!name.equals(qName)) {
tempStack.push(name);
name = stack.pop();
}
while(!tempStack.empty()) {
stack.push(tempStack.pop());
}
}

public void characters (char ch[], int start, int length)
throws SAXException
{
String text = new String(ch, start, length);
writer.println(" text: " + text);
}

public static void main(String[] args) throws Exception {
Main dh = new Main();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();

StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<root name=\"attr\">")
.append("<name>TEST XML</name>")
.append("<user>")
.append("<name>Solnone</name>")
.append("</user>")
.append("</root>");
byte[] buf = sb.toString().getBytes("UTF-8");

InputStream is = new ByteArrayInputStream(buf);
try {
parser.parse(is, dh);
} finally {
is.close();
}
}

}

/*
tag: /root
attribute: name value:attr
tag: /root/name
text: TEST XML
tag: /root/user
tag: /root/user/name
text: Solnone
*/

沒有留言:

網誌存檔