Kyanite
Kyanite

Reputation: 746

Cannot parse XML file from URL using SAX?

I read an XML file from a URL then pass it on to a SAX document. However it's almost as if the parsing does not occur and I cannot figure out why?

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;
            }
        }
    }

From what I can see, once the .parse() method is called, the contents of the <to></to> tags should be printed out, but it isn't. Any ideas what's going wrong here?

Upvotes: 1

Views: 523

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

Your override of the startElement method has the wrong signature, therefore it overrides nothing and the default is being called.

Java has the @Override annotation, which you use when overriding a superclass method, allowing the compiler to verify that you have the (or at least a) correct signature.

enter image description here

The correct signature is:

    public void startElement(
        String uri, 
        String rawName, 
        String qname, 
        Attributes attributes) throws SAXException {
    ...

Upvotes: 1

Related Questions