Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to parse an XML string and display it in a EditText but I can't, I not understand what could be the problem, please a bit help, my code :

private String xmlc = "<game><cel>5</cel><val>2</val></game>";

private CharSequence readXML(String xmlc2) throws XmlPullParserException {


    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    XmlPullParser xpp = factory.newPullParser();

    String results = "";
    String celda = "";
    String valor = "";

    xpp.setInput(new StringReader (xmlc2));
    int eventType = xpp.getEventType();
    String tagName = xpp.getName();

    try {       
        while (eventType != XmlPullParser.END_DOCUMENT) {

            if(tagName.equalsIgnoreCase("cell")){
                celda = xpp.nextText();
            } else if(tagName.equalsIgnoreCase("val")){
                valor = xpp.nextText();
            }       
            xpp.nextTag();      
        }       
    } catch (Exception e) {
        Toast.makeText(this, "error!", Toast.LENGTH_LONG).show();
    }
    return celda;
}

Thanks for the suggestion, now I can send the string xml as parameter and I can to parse, but I don't know how save the 2 values found and show each value in different EditText?

private EditText et02;
private EditText et03;
private String xmlc = "<game><cel>5</cel><val>2</val></game>";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    EditText et02 = (EditText)findViewById(R.id.et02);
    EditText et03 = (EditText)findViewById(R.id.et03);

    TextView myXmlContent = (TextView)findViewById(R.id.xml_tv);
    String stringXmlContent;

    stringXmlContent = getAllXML();
    myXmlContent.setText(stringXmlContent);

}
public String getAllXML(){

    Activity activity = this;
    String str = "";

    //For file source
    //Resources res = activity.getResources();
    //XmlResourceParser xpp = res.getXml(R.xml.test);


    try {
        //For String source
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(new StringReader(xmlc)); 

        xpp.next();
        int eventType = xpp.getEventType();                        

          while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
              if (xpp.getEventType()==XmlPullParser.START_TAG) {
                  if (xpp.getName().equals("cel")) {
                      str += "\ncell : "+xpp.nextText();
                  }
                  if (xpp.getName().equals("val")) {
                      str += "\nval : "+xpp.nextText();                       
                  }
              }
              xpp.next();
          }

    } catch (XmlPullParserException e) {
          e.printStackTrace();
    } catch (IOException e) {
          e.printStackTrace();
    }
    return str;
}
share|improve this question
    
And what's the problem? –  Egor Apr 22 '13 at 7:53
    
You're using xmlc2 in your code instead of xmlc (if its not in an other class) und search for "cell" instead of "cel" like in your xml. –  luxer Apr 22 '13 at 8:10
    
i do not know how to retrieve the values ​​"celda" and "valor" for display in the textview, also i add "Toasts" in the bucle while to display the values ​​but I do not show anything. In short I want to send a parameter as input and get 2 values as output. –  user2287189 Apr 22 '13 at 9:00
    
i'm trying this for see the tags : String celda = xpp.nextText(); Toast.makeText(this, celda, Toast.LENGTH_LONG).show(); ...is wrong or ok ? –  user2287189 Apr 22 '13 at 9:05
    
You should better debug your application in eclipse with breakpoints. Toasts are not the best choise. Or use Log.d("LOGTAG", "some msg here"); you can read this in the ddms. –  rekire Apr 22 '13 at 9:15

3 Answers 3

// call web api and try below code for xml parsing

new GettingData().execute();

private class GettingDataextends AsyncTask<String, String, String> {

        private static final String PLACEMARK = "Placemark";
        private static final String NAME = "name";
        private static final String DESCRIPTION = "description";
        private static final String COORDINATES = "coordinates";
        private ProgressDialog progressDialog;
        private String serverName, trackName;


        @Override
        protected void onPreExecute() {

            super.onPreExecute();
                progressDialog = new ProgressDialog(mContext);
                progressDialog.setMessage("Loading ...");
                progressDialog.setIndeterminate(false);
                progressDialog.setCancelable(false);
                progressDialog.show();


        }

        @Override
        protected String doInBackground(String... args) {

            try {

                url = "Your_Url_Here";

                XMLParser parser1 = new XMLParser();
                String xml = parser1.getXmlFromUrl(url); // getting XML

                XmlPullParserFactory factory = XmlPullParserFactory
                        .newInstance();
                factory.setNamespaceAware(true);
                XmlPullParser parser = factory.newPullParser();

                parser.setInput(new StringReader(xml));

                int eventType = parser.getEventType();
                Model mModel = null;
                while (eventType != XmlPullParser.END_DOCUMENT) {

                    String name = null;
                    switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        name = parser.getName();
                        if (name.equalsIgnoreCase(PLACEMARK)) {
                            mModel = new Model();
                        } else if (mModel != null) {
                            if (name.equalsIgnoreCase(NAME)) {
                                mModel.setName(parser
                                        .nextText());
                            } else if (name.equalsIgnoreCase(DESCRIPTION)) {
                                mModel.setDescription(parser
                                        .nextText());
                            } else if (name.equalsIgnoreCase(COORDINATES)) {
                                mModel.setCoordinates(parser
                                        .nextText());
                            }
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        name = parser.getName();
                        if (name.equalsIgnoreCase(PLACEMARK)
                                && mModel != null) {

                            if (!mPlaceMarkSingleDriver.getName()
                                    .equalsIgnoreCase("null")) {
                                Constance.mArryList                                         .add(mModel);
                            }

                        }
                        break;
                    }
                    eventType = parser.next();
                }

            } catch (Exception e) {


                    progressDialog.dismiss();


            }

            return null;

        }

        @Override
        protected void onPostExecute(String result) {

            progressdialog.dismiss();
    }

// XmlParse class

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

    // constructor
    public XMLParser() {

    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {     
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}
share|improve this answer

you did not update the tagname inside the while loop try this:

     while (eventType != XmlPullParser.END_DOCUMENT) {

       if(tagName.equalsIgnoreCase("cell")){
            celda = xpp.nextText();
        } else if(tagName.equalsIgnoreCase("val")){
            valor = xpp.nextText();
        }       
        xpp.nextTag();  
        tagname=xpp.getName();    
    }
share|improve this answer

SAX parser is way much efficient and Faster than Pullparser. SAX is always the best option when parsing XML in android. you can use this tutorial for SAX parsing

http://www.technotalkative.com/android-sax-parsing-example/

share|improve this answer
    
Thanks for the suggestion, –  user2287189 Apr 23 '13 at 14:50
    
according to documentation in android developer the best one in android is XMLPULLPARSER developer.android.com/training/basics/network-ops/xml.html –  Hamid Reza Jun 29 at 11:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.