我已经制作了一个Xml解析应用程序。但是当我运行源代码时,它显示一个空白屏幕

时间:2011-07-04 17:12:23

标签: android xml parsing

第一项活动

package com.example.parserss;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;


public class Parserss extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);

        try {
            URL url = new URL("http://www.w3schools.com/xml/note.xml");
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            xr.parse(new InputSource(url.openStream()));
            MHandler mhandler = new MHandler();
            xr.setContentHandler(mhandler);
            getValue getV = mhandler.getData();
            tv.setText(getV.toString());
        }
        catch(Exception e) {
            System.out.println("Exception Occured :" + e );
        }

       this.setContentView(tv);


    }
}

第二项活动

package com.example.parserss;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MHandler extends DefaultHandler {
    Boolean outerElement = false;
    Boolean innerElement = false;

    private getValue getvalue = new getValue();

    public getValue getData() {
        return getvalue;
    }

     public void startDocument() throws SAXException {
         getvalue = new getValue();
 }

 @Override
 public void endDocument() throws SAXException {
         // Nothing to do
 }




   public void startElement(String uri , String localName , String qName, Attributes attr) throws SAXException {


       if(localName.equals("note")) {
           outerElement = true;

       }
       else if(localName.equals("to")) {
           innerElement = true;

       }
   }
   public void endElement(String uri, String localName, String qnqme) throws SAXException {

       if(localName.equalsIgnoreCase("note")) {
           outerElement = false;
          }
       else if (localName.equals("body")) {
           innerElement = false;
       }



   }
   public void characters(char[] ch , int start, int length) throws SAXException {
       if(innerElement){
           getvalue.setStringss(new String(ch, start, length));


       }

   }
}

第3次活动

package com.example.parserss;

public class getValue {
    private String exData = null;
    public String getStringss() {
        return  exData;
    }
    public void setStringss(String exData) {
        this.exData = exData;

    }
    public String toString() {
        return "data = " + exData;
    }
}

1 个答案:

答案 0 :(得分:0)

我得到了解决方案。实际上我首先解析流然后创建错误的处理程序类对象。首先,我们必须创建处理程序类的对象,然后解析流并且它可以工作。