CHAPTER 9 ■ WRITING AND READING XML
// If we're not at the end of the attributes,
// add a comma, for proper formatting if (i < attributes.getLength() - 1) {
sb.append(", ");
}
}
}
// Describe the element in the console System.out.println(sb.toString());
}
}
Again, we're using a StringBuilder to avoid creating an excess of String objects in memory. The
only complexity comes when we work through any attributes that may be present, and most of the code
is really just for “pretty printing” (a phrase that programmers often use when referring to code that
formats output to be easily read by humans).
Let's look at the class that uses the XMLToConsoleHandler class to write to the console. Again, you
need to have a file named poemsource.xml in the C:\test (on Windows) or C:/test (on Unix or Linux)
directory. You can use the contents of the domoutput.xml file as the contents of the poemsource.xml
file. Here's that class:
Listing 9-8. ReadWithSAX
package com.bryantcs.examples.xml;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class ReadWithSAX {
public static void main(String[] args) {
String fileName = "C:" + File.separator + "test"
- File.separator + "poemsource.xml";
getFileContents(fileName);
}
private static void getFileContents (String fileName) {
try {
// Make an instance of our handler XMLToConsoleHandler handler = new
XMLToConsoleHandler();
// Get a parser factory SAXParserFactory factory = SAXParserFactory.newInstance();
// Get a parser SAXParser saxParser = factory.newSAXParser();
// And now parse the file with our handler saxParser.parse(fileName, handler );