How to parse xml string with xmlpullparser android

无人久伴 提交于 2019-12-05 09:39:30

问题


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;
}

回答1:


// 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));
        }
}



回答2:


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();    
}


来源:https://stackoverflow.com/questions/16141931/how-to-parse-xml-string-with-xmlpullparser-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!