日期:2014-05-17  浏览次数:20675 次

sax解析xml时覆盖defaultHandler时的问题
为什么在 4设置内容处理器
 reader.setContentHandler(new TagValueHandler());时会出现错误提示:

No enclosing instance of type saxReader2 is accessible. Must qualify the allocation with an enclosing instance of type saxReader2 (e.g. x.new A() where x is an instance of saxReader2).

还有在用eclipse时,覆盖defaultHandler的时候为什么参数列表都是arg,而没有明确地列出:url ,localname,name呢?

Java code
package cn.xushuai.sax;

<?xml version="1.0" encoding="UTF-8" standalone="no"?><exam>
    <student examid="1111" idcard="0001">
        <name>张三</name>
        <location>北京</location>
        <grade>90</grade>
    </student>

    <student examid="2222" idcard="0002">
        <name>李四</name>
        <location>上海</location>
        <grade>93</grade>
    </student>


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.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class saxReader2 {

    public static void main(String args) throws ParserConfigurationException, SAXException, IOException {
        // TODO Auto-generated constructor stub
    
    //1.创建解析工厂
        SAXParserFactory factory = SAXParserFactory.newInstance();
        
    //2.获取解析器
        SAXParser sp = factory.newSAXParser();
        
    //3.得到读取器
        XMLReader reader = sp.getXMLReader();
        
        //4.设置内容处理器
        reader.setContentHandler(new TagValueHandler());
    
        //5.读取xml文档内容
        reader.parse("src/exam.xml");
    }
    
    class TagValueHandler extends DefaultHandler{

        private String currentTag;
        private int neednumber = 2;
        private int currentNumber=0;
        
        
        @Override
        public void startElement(String arg0, String arg1, String arg2,
                Attributes arg3) throws SAXException {
            
            currentTag = arg2;
            if(currentTag.equals("作者"))
                currentNumber++;
        }
        
        
        @Override
        public void characters(char[] arg0, int arg1, int arg2)
                throws SAXException {
            if("作者".equals(currentTag)&& currentNumber==neednumber){
                
                System.out.println(new String(arg0,arg1,arg2));
            }
        }

        @Override
        public void endElement(String arg0, String arg1, String arg2)
                throws SAXException {
            currentTag= null;
        }
                
    }
}



------解决方案--------------------
错误。
class TagValueHandler前面加static

还有在用eclipse时,覆盖defaultHandler的时候为什么参数列表都是arg,而没有明确地列出:url ,localname,name呢?
这个因为Eclipse里没有指定DefaultHandler的源代码。
它不知道变量名字。 如果你添加了源代码就可以了。