Skip to content Skip to sidebar Skip to footer

Android: Parse Xml From String Problems

I've got a custom contentHandler (called XMLHandler), I've been to a lot of sites via Google and StackOverflow that detail how to set that up. What I do not understand is how to US

Solution 1:

Here is one example i hope it will be usefull to understand "SAXParser"

package test.example;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

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

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

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

publicclassXMLParsingDemoextendsActivity {

    privatefinalStringMY_DEBUG_TAG="WeatherForcaster";

    /** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle icicle) {
        super.onCreate(icicle);

        /* Create a new TextView to display the parsingresult later. */TextViewtv=newTextView(this);

        try {
            /* Create a URL we want to load some xml-data from. */DefaultHttpClienthc=newDefaultHttpClient();  
        ResponseHandler <String> res = newBasicResponseHandler();  
        HttpPostpostMethod=newHttpPost("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
        String response=hc.execute(postMethod,res); 

        /* Get a SAXParser from the SAXPArserFactory. */SAXParserFactoryspf= SAXParserFactory.newInstance();
        SAXParsersp= spf.newSAXParser();

        /* Get the XMLReader of the SAXParser we created. */XMLReaderxr= sp.getXMLReader();
        /* Create a new ContentHandler and apply it to the XML-Reader*/ExampleHandlermyExampleHandler=newExampleHandler();
        xr.setContentHandler(myExampleHandler);

        /* Parse the xml-data from our URL. */InputSourceinputSource=newInputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(newStringReader(response));

        /* Parse the xml-data from our URL. */
        xr.parse(inputSource);
        /* Parsing has finished. *//* Our ExampleHandler now provides the parsed data to us. */ParsedExampleDataSetparsedExampleDataSet= myExampleHandler.getParsedData();


        /* Set the result to be displayed in our GUI. */
        tv.setText(response + "\n\n\n***************************************" + parsedExampleDataSet.toString());



        } catch (Exception e) {
            /* Display any Error to the GUI. */
            tv.setText("Error: " + e.getMessage());
            Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
        }
        /* Display the TextView. */this.setContentView(tv);
    }

    publicclassExampleHandlerextendsDefaultHandler {

        // ===========================================================// Fields// ===========================================================privatebooleanin_outertag=false;
        privatebooleanin_innertag=false;
        privatebooleanin_mytag=false;

        privateParsedExampleDataSetmyParsedExampleDataSet=newParsedExampleDataSet();

        // ===========================================================// Getter & Setter// ===========================================================public ParsedExampleDataSet getParsedData() {
            returnthis.myParsedExampleDataSet;
        }

        // ===========================================================// Methods// ===========================================================@OverridepublicvoidstartDocument()throws SAXException {
            this.myParsedExampleDataSet = newParsedExampleDataSet();
        }

        @OverridepublicvoidendDocument()throws SAXException {
            // Nothing to do
        }

        /** Gets be called on opening tags like: 
         * <tag> 
         * Can provide attribute(s), when xml was like:
         * <tag attribute="attributeValue">*/@OverridepublicvoidstartElement(String uri, String localName, String qName, org.xml.sax.Attributes atts)throws SAXException {
            super.startElement(uri, localName, qName, atts);
            if (localName.equals("outertag")) {
                this.in_outertag = true;
            }
            elseif (localName.equals("innertag")) {
                StringattrValue= atts.getValue("sampleattribute");
                myParsedExampleDataSet.setExtractedString(attrValue);
                this.in_innertag = true;
            }
            elseif (localName.equals("mytag")) {
                this.in_mytag = true;
            }
            elseif (localName.equals("tagwithnumber")) {
                // Extract an AttributeStringattrValue= atts.getValue("thenumber");
                inti= Integer.parseInt(attrValue);
                myParsedExampleDataSet.setExtractedInt(i);
            }

        }


        /** Gets be called on closing tags like: 
         * </tag> */@OverridepublicvoidendElement(String namespaceURI, String localName, String qName)throws SAXException {
            if (localName.equals("outertag")) {
                this.in_outertag = false;
            }elseif (localName.equals("innertag")) {
                this.in_innertag = false;
            }elseif (localName.equals("mytag")) {
                this.in_mytag = false;
            }elseif (localName.equals("tagwithnumber")) {
                // Nothing to do here
            }
        }       


        /** Gets be called on the following structure: 
         * <tag>characters</tag> */@Overridepublicvoidcharacters(char ch[], int start, int length) {
            if(this.in_mytag){
                myParsedExampleDataSet.setExtractedString(newString(ch));
            }
        }
    }

    publicclassParsedExampleDataSet {
        privateStringextractedString=null;
        privateintextractedInt=0;

        public String getExtractedString() {
            return extractedString;
        }
        publicvoidsetExtractedString(String extractedString) {
            this.extractedString = extractedString;
        }

        publicintgetExtractedInt() {
            return extractedInt;
        }
        publicvoidsetExtractedInt(int extractedInt) {
            this.extractedInt = extractedInt;
        }

        public String toString(){
            return"\n\n\nExtractedString = " + this.extractedString
                    + "\n\n\nExtractedInt = " + this.extractedInt;
        }

    }

}

Solution 2:

You have to access your XML data into handler which you have define by XMLHandler()

you have to override

publicvoidstartElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException {

}


@OverridepublicvoidendElement(String namespaceURI, String localName, String qName) {

}

and

@Overridepublicvoidcharacters(char ch[], int start, int length) {

    }

Post a Comment for "Android: Parse Xml From String Problems"