Java与XML原来可以这么简单基于XMLPull的解析器

XmlPull和Sax类似,是基于流(stream)操作文件,然后根据节点事件回调开发者编写的处理程序。因为是基于流的处理,因此Xmlpull和Sax都比较节约内存资源,不会象Dom那样要把所有节点以对橡树的形式展现在内存中。

但Xmlpull比Sax更简明,而且不需要扫描完整个流。现在XmlPull是一开源项目,并成为了Google android类库的一部分,想了解更多请查看http://www.xmlpull.org。XmlPull的jar以及源文件见附件。

XmlPull使用起来很简单,下面献上一自己写的实例,xml数据由google weather api提供:http://easymorse.googlecode.com/svn/tags/android.xmlpull.google.weather-1.0/assets/weather.xml

Java代码 收藏代码
public class xmlPuller {

public static void main(String[] args) {  
    XmlPullParser xpp = null;  
    String url = "http://easymorse.googlecode.com/svn/tags/android.xmlpull.google.weather-1.0/assets/weather.xml";  
    String filename = "weather.xml";  
    FileInputStream fis = null;  
    InputStream is = null;  
    try {  
        if(getRemoteFile(url,filename)){  
            fis = new FileInputStream(new File("weather.xml"));  
            is = new BufferedInputStream(fis);   
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
            factory.setNamespaceAware(true);  
            xpp = factory.newPullParser();  
            xpp.setInput(is,"utf-8");  
            int type = xpp.getEventType();  
            StringBuilder sb = new StringBuilder();  
            while(type!=XmlPullParser.END_DOCUMENT){  
                switch(type){  
                case XmlPullParser.START_DOCUMENT:  
                    sb.append("Start document");  
                    break;  
                case XmlPullParser.START_TAG:  
                    sb.append("Start tag:" + xpp.getName() + "\n");  
                    for(int i=0;i

运行时经常会遇到以下的异常:

Java代码 收藏代码
caused by: org.xmlpull.v1.XmlPullParserException: resource not found: /META-INF/services/org.xmlpull.v1.XmlPullParserFactory make sure that parser implementing XmlPull API is available; nested exception is:
org.xmlpull.v1.XmlPullParserException: resource not found: /META-INF/services/org.xmlpull.v1.XmlPullParserFactory make sure that parser implementing XmlPull API is available
at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:278)
at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java:259)
at xmlPuller.main(xmlPuller.java:28)

XmlPullParserException:resource not found!

没有找到这样的资源:META-INF/services/org.xmlpull.v1.XmlPullParserFactory

so,我们就为它添加这样的资源:

   将http://kxml.sourceforge.net/下载的kxml2.jar加到你的项目中即可。

 kxml2.jar就包含了META-INF/services/org.xmlpull.v1.XmlPullParserFactory文件,它的内容其实就是一句话:

  org.kxml2.io.KXmlParser,org.kxml2.io.KXmlSerializer

下载链接已经不存在了!

你可能感兴趣的:(java基础,java)