sax解析的小问题,求高手指点
本帖最后由 u011237944 于 2013-08-21 15:41:56 编辑
用SAXParser解析可以通过,用XMLReader.parse(String systemId)解析却显示java.net.MalformedURLException: unknown protocol: d错误,这个systemId参数该如何写,求高手解答。
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
public class TestSAX {
public static void main(String[] args){
/*SAXParserFactory fac=SAXParserFactory.newInstance();
SAXParser par=null;
try{
par=fac.newSAXParser();
par.parse(new File("D:/Program Files/MyEclipseSpace/test/src/xml_demo_01.xml"), new MySAX());
}
catch(Exception e){
e.printStackTrace();
}*/
XMLReader reader=null;
SAXHandler saxhdl=new SAXHandler();
try{
reader=XMLReaderFactory.createXMLReader();
reader.setContentHandler(saxhdl);
reader.parse("D:/Program Files/MyEclipseSpace/test/src/xml_demo_01.xml");//java.net.MalformedURLException: unknown protocol: d
}
catch(Exception e){
e.printStackTrace();
}
}
}
class SAXHandler extends DefaultHandler{
public SAXHandler(){
super();
}
public void startDocument() throws SAXException{
System.out.println("SAX start:");
}
public void endDocument() throws SAXException{
System.out.println("\nSAX end.");
}
public void startElement(String uri,String localName,String qName,Attributes attr) throws SAXException{
System.out.print("<"+qName);
if(attr!=null){
for(int i=0;i<attr.getLength();i++){
System.out.print(" "+attr.getQName(i)+"="+attr.getValue(i));
}
}
System.out.print(">");
}
public void endElement(String uri,String localName,String qName) throws SAXException{
System.out.println("</"+qName+">");
}
public void charactors(char[] ch,int start,int length) throws SAXException{
System.out.print(new String(ch,start,length));
}
}
错误信息:
java.net.MalformedURLException: unknown protocol: d
at java.net.URL.<init>(URL.java:574)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:650)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:186)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1132)
at TestSAX.main(TestSAX.java:32)
[解决办法]
InputSource inputSource = new InputSource(new FileReader("D:\\a.xml"));
xmlReader.parse(inputSource);