无法在SAXParser中解析文件和处理程序

时间:2015-04-20 16:23:24

标签: java xml sax saxparser

我将一个XML文件和一个处理程序传递给SAXParser,但是我收到了这个错误: Cannot resolve method 'parse(java.io.File, jdk.internal.org.xml.sax.helpers.DefaultHandler)'

parse方法的属性定义为(File,DefaultHandler),它们完全匹配,所以我不确定我哪里出错了。这是完整的方法:

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

1 个答案:

答案 0 :(得分:1)

它应该是org.xml.sax.helpers.DefaultHandler 不是jdk.internal...

所以

import org.xml.sax.helpers.DefaultHandler;

您可能还应该定义扩展DefaultHandler的类,而不仅仅是内联它。