我从URL读取XML文件,然后将其传递给SAX文档。然而,几乎就好像解析没有发生,我无法弄清楚为什么?
XMLReader myReader = XMLReaderFactory.createXMLReader();
LetterHandler rh = new LetterHandler();
myReader.setContentHandler(rh);
URL url2 = new URL("http://www.w3schools.com/xml/note.xml");
InputStream stream = url2.openStream();
System.out.println(stream.available());
myReader.parse(new InputSource(stream));
class LetterHandler extends DefaultHandler {
Boolean toSeen = false;
String to;
public void startElement(String localName, String rawName, Attributes attributes) throws SAXException {
if (rawName.equals("to")) {
System.out.println(rawName);
toSeen = true;
}
}
public void characters(char[] ch, int start, int length) {
if (toSeen) {
System.out.println("To: " + new String(ch, start, length));
toSeen = false;
}
}
}
从我所看到的情况来看,一旦调用了.parse()方法,就应该打印出<to></to>
标签的内容,但事实并非如此。任何想法在这里出了什么问题?