我用eclipse建了个项目:写了个用SAX处理XML的类,可是运行时报错:java.net.MalformedURLException: no protocol:product.xml,帮我看看是因为什么啊?
Product.java
package com.leeg.bean;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
class SAXParserHandler extends DefaultHandler{
public void startDocument()throws SAXException{
System.out.println("起始文档");
}
public void endDocument()throws SAXException{
System.out.println("结束文档");
}
public void characters(char[]ch ,int start,int length)throws SAXException{
String charString =new String(ch,start,length);
System.out.println("字符:"+charString);
}
public void startElement(String namespaceURI ,String localName,String qName,
Attributes atts)throws SAXException{
System.out.println("起始元素:"+qName);
for(int i=0;i<atts.getLength();i++){
System.out.println("属性值:"+atts.getValue(i));
}
}
public void endElement(String namespaceURI ,String localName,String qName)throws SAXException{
System.out.println("结束元素:"+qName);
}
}
public class Product {
public static void main(String[] args) throws Exception {
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
parser.parse("product.xml",new SAXParserHandler());
}
}
我的product.xml文件:(在我的项目目录下面啊)
<?xml version="1.0" encoding="UTF-8"?>
<product name="Speakers">
<quantity>3</quantity>
<price>1500</price>
</product>
运行结果为:
结束文档
java.net.MalformedURLException: no protocol: product.xml
at java.net.URL.<init>(URL.java:579)
at java.net.URL.<init>(URL.java:476)
at java.net.URL.<init>(URL.java:425)
at gnu.xml.aelfred2.XmlParser.pushURL(XmlParser.java:3414)
at gnu.xml.aelfred2.XmlParser.doParse(XmlParser.java:159)
at gnu.xml.aelfred2.SAXDriver.parse(SAXDriver.java:320)
at gnu.xml.aelfred2.XmlReader.parse(XmlReader.java:294)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:223)
at com.leeg.bean.Product.main(Product.java:45)
Exception in thread "main"
照着一本资料书来做的,可是不行啊,为什么?
------解决方法--------------------------------------------------------
你的xml文件是不是用UltralEdit编辑的?
这个是ue的bug,字符编码有问题。
你现在可以使用写字板打开这个xml保存一下。