如何使用xmlpullparser android解析xml字符串

时间:2013-04-22 07:48:28

标签: android string xml-parsing xmlpullparser

我想解析XML字符串并将其显示在EditText中,但我不能,我不明白可能是什么问题,请帮助我,我的代码:

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

感谢您的建议,现在我可以发送字符串xml作为参数,我可以解析,但我不知道如何保存找到的2个值并在不同的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;
}

2 个答案:

答案 0 :(得分:4)

//调用web api并尝试下面的代码进行xml解析

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类

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

答案 1 :(得分:0)

你没有更新while循环中的标记名试试这个:

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