reader.setContentHandler(new ListHandler());这个第26行代码显示错误,然后运行后显示这样的错误: Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type Demo1 is accessible. Must qualify the allocation with an enclosing instance of type Demo1 (e.g. x.new A() where x is an instance of Demo1). at cn.zhangzhensax.xml.Demo1.main(Demo1.java:26)
reader.setContentHandler(new ListHandler());这个第26行代码显示错误,然后运行后显示这样的错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type Demo1 is accessible. Must qualify the allocation with an enclosing instance of type Demo1 (e.g. x.new A() where x is an instance of Demo1). at cn.zhangzhensax.xml.Demo1.main(Demo1.java:26)
package cn.zhangzhensax.xml;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
public class Demo1 {
//SAX解析xml文档
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
//1.创建解析工厂
SAXParserFactory factory=SAXParserFactory.newInstance();
//2.得到解析器
SAXParser par=factory.newSAXParser();
//3.得到阅读器
XMLReader reader=par.getXMLReader();
//4.设置内容处理器
reader.setContentHandler(new ListHandler());
//5.读取Xml文档内容
reader.parse("src/demo1.xml");
}
}class ListHandler implements ContentHandler{
@Override
public void setDocumentLocator(Locator locator) {
// TODO Auto-generated method stub
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
System.out.println("<"+qName+">");
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.println("</"+qName+">");
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.println(new String(ch,start,length));
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void processingInstruction(String target, String data)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void skippedEntity(String name) throws SAXException {
// TODO Auto-generated method stub
}
}
在这里是main里面不能访问非static的内部类ListHandler
把ListHandler 改成static的就行了
也就是32行改成static class ListHandler implements ContentHandler {