import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.Handler.MyHandler;
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
MyHandler handler = new MyHandler(nodeName);
// 這裡出錯The method parse(InputStream, HandlerBase) in the type SAXParser is not applicable for the arguments (InputStream, MyHandler)
parser.parse(inputStream, handler);
Sax解析xml的話,SAXParser它的parse方法的聲明為parse(InputSource is, DefaultHandler dh) 使用指定的 DefaultHandler 將給定 InputSource 的內容解析為 XML。通常我們需要自己實現DefaultHandler接口。你傳入的MyHandler的話,這個類需要繼承DefaultHandler類,然後按照自己的業務邏輯重寫一些必要的方法。
Java使用SAX的一個例子代碼,生成SAXParser、生成Handler實例、解析文件、為過濾器設置解析器、打印該元素節點所有屬性等。
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.apache.xerces.parsers.*;
public class SAXDemo extends DefaultHandler
{
public static void main(String[] args)
{
try
{
//生成SAXParser
SAXParser parser=(SAXParser)Class.
forName("org.apache.xerces.parsers.SAXParser").
newInstance();
SAXDemo handler=new SAXDemo();
//生成Handler實例
FilterHandler filter=new FilterHandler();
parser.setContentHandler(handler);
System.out.println("\nNow the parser is working...\n");
//解析文件
parser.parse("TestXerces.xml");
System.out.println("\nNow the filter is working ...\n");
//為過濾器設置解析器
filter.setParent(parser);
//為過濾器設置處理器
filter.setContentHandler(handler);
//解析文件
filter.parse("TestXerces.xml");
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public void startElement
(String uri,String localName,String qName,Attributes attr)
{
System.out.println("start of a Element --> uri: "+
uri+" localName: "+localName+" qName: "+qName);
//打印該元素節點所有屬性
if(attr.getLength()>0)
{
for(int i=0;i<attr.getLength();i++)
{
System.out.println("\t...with attribute --> "+
attr.getQName(i)+"="+attr.getValue(i));
}
}
}
public void endElement
(String uri,String localName,String qName)
{
System.out.println("end of a Element --> uri: "+uri+
" localName: "+localName+" qName: "+qName);
}
static class FilterHandler extends XMLFilterImpl
{
int index=0;
public void startElement
(String uri,String localName,String qName,Attributes attr)
throws SAXException
{
AttributesImpl attrImpl=new AttributesImpl(attr);
for (int i=0;i<attrImpl.getLength();i++)
{
//檢查是否有ID屬性
if(attrImpl.getQName(i).toUpperCase().equals("ID"))
{
attrImpl.removeAttribute(i);
break;
}
}
//新建ID屬性
attrImpl.addAttribute
("","id","id","ID",String.valueOf(index++));
super.startElement(uri,localName,qName,attrImpl);
}
public void endElement
(String uri,String localName,String qName)
throws SAXException
{
super.endElement(uri,localName,qName);
}
public void characters(char[] ch,int iStart,int iLength)
throws SAXException
{
super.characters(ch,iStart,iLength);
}
}
}