Search code examples
javaxmlsaxsaxparser

Can't parse File and Handler in SAXParser


I'm passing in an XML file and a handler to the SAXParser but I'm getting this error: Cannot resolve method 'parse(java.io.File, jdk.internal.org.xml.sax.helpers.DefaultHandler)'

The attributes for the parse method are defined as (File, DefaultHandler) which match exactly, so I'm not sure where I'm going wrong. Here is the full method:

public String readXML (File readFile) throws Exception {
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxFactory.newSAXParser();
    final String outputString = "";
    DefaultHandler handler = new DefaultHandler() {
        boolean bArtist    = false;
        boolean bAlbumName = false;
        boolean bYear      = false;
        boolean bGenre     = false;

        public void startElement(String uri, String localName, String qName, Attributes attr)
                throws SAXException {
            if (qName.equalsIgnoreCase("ARTIST"))    { bArtist = true; }
            if (qName.equalsIgnoreCase("ALBUMNAME")) { bAlbumName = true; }
            if (qName.equalsIgnoreCase("YEAR"))      { bYear = true; }
            if (qName.equalsIgnoreCase("GENRE"))     { bGenre = true; }
        }
        public void characters(char ch[], int start, int length) {
            if (bArtist) {
                outputString.concat("Artist: " + new String(ch,start,length) + "\n");
            }
            if(bAlbumName) {
                outputString.concat("Album: " + new String(ch,start,length) + "\n");
            }
            if(bYear) {
                outputString.concat("Year: " + new String(ch,start,length) + "\n");
            }
            if(bGenre) {
                outputString.concat("Genre: " + new String(ch,start,length) + "\n");
            }
            outputString.concat("\n");
        }
    };

    saxParser.parse(readFile,handler);
    return outputString;
}

Solution

  • It should be org.xml.sax.helpers.DefaultHandler not jdk.internal...

    so

    import org.xml.sax.helpers.DefaultHandler;
    

    You should probably also define the class that extends the DefaultHandler not just inline it.