具体实现 被观察者对象ParseXMLSubject类:
package test;
import java.io.*;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.*;
public class ParseXMLSubject implements XMLReader {
ContentHandler handler;
String nsu = "";
Attributes atts = new AttributesImpl();
String rootElement = "addressbook";
String indent = "\n ";
public ParseXMLSubject(){
}
public ContentHandler getContentHandler() {
return handler;
}
public void parse(InputSource input) throws IOException, SAXException {
try {
// Get an efficient reader for the file
java.io.Reader r = input.getCharacterStream();
BufferedReader br = new BufferedReader(r);
// Read the file and display it's contents.
String line = br.readLine();
while (null != (line = br.readLine())) {
if (line.startsWith("email:")) {
break;
}
}
if (handler == null) {
throw new SAXException("No content handler");
}
// Note:
// We're ignoring setDocumentLocator(), as well
handler.startDocument();
handler.startElement(nsu, rootElement, rootElement, atts);
output("email", line);
line = br.readLine();
output("html", line);
line = br.readLine();
output("firstname", line);
line = br.readLine();
output("lastname", line);
line = br.readLine();
output("work", line);
line = br.readLine();
output("home", line);
line = br.readLine();
output("fax", line);
line = br.readLine();
output("pager", line);
line = br.readLine();
output("cell", line);
handler.ignorableWhitespace("\n".toCharArray(), 0, // start index
1 // length
);
handler.endElement(nsu, rootElement, rootElement);
handler.endDocument();
} catch (Exception e) {
e.printStackTrace();
}
}
public void parse(String systemId) throws IOException, SAXException {
}
public DTDHandler getDTDHandler() {
return null;
}
public EntityResolver getEntityResolver() {
return null;
}
[1] [2] 下一页