Java Reference
In-Depth Information
}
public void ignorableWhitespace(char[] ch, int start, int length) {
System.out.println("Ignorable whitespace: " + new String(ch, start, length));
}
}
Each handler method just outputs information about the event to the command line. Now we can define
a program to use a handler of this class type to parse an XML document. We will make the example
read the name of the XML file from the command line. Here's the code:
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
public class TrySAXHandler {
public static void main(String args[]) {
if(args.length == 0) {
System.out.println("No file to process. Usage is:"
+"\njava TrySax \"filename\" ");
return;
}
File xmlFile = new File(args[0]);
process(xmlFile);
}
private static void process(File file) {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = null;
spf.setNamespaceAware(true);
spf.setValidating(true);
System.out.println("Parser will "+(spf.isNamespaceAware()?"":"not ")
+ "be namespace aware");
System.out.println("Parser will "+(spf.isValidating()?"":"not ")
+ "validate XML");
try {
parser = spf.newSAXParser();
System.out.println("Parser object is: "+ parser);
} catch(SAXException e) {
e.printStackTrace(System.err);
System.exit(1);
} catch(ParserConfigurationException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.out.println("\nStarting parsing of "+file+"\n");
Search WWH ::




Custom Search