Android XML Parser不太适用

时间:2013-10-23 00:57:28

标签: java android xml parsing url

我需要将XML数据解析为String [],以便我可以在下拉自动完成文本视图中显示它。我试过JDOM,但它对我不起作用。我停在另一个解析器上:http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/ 我只用我需要的东西重新编写代码 所以现在我有以下文件:     package com.example.selptimetableproject.ivo.dimitrov;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

enter code here import android.widget.ArrayAdapter;     import android.widget.AutoCompleteTextView;

public class browse_courses extends Activity {
    // All static variables
        static final String URL = "http://www.inf.ed.ac.uk/teaching/courses/selp/xml/courses.xml";
// XML node keys
static final String KEY_ITEM = "course"; // parent node
static final String KEY_DRPS = "drps";
static final String KEY_NAME = "name";
static final String KEY_URL = "url";
static final String KEY_ACR = "acronym";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    setContentView(R.layout.activity_browse_courses);

    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    // looping through all item nodes <course>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        map.put(KEY_DRPS, parser.getValue(e, KEY_DRPS));
        map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
        map.put(KEY_URL, parser.getValue(e, KEY_URL));
        map.put(KEY_ACR, parser.getValue(e, KEY_ACR));

        // adding HashList to ArrayList
        menuItems.add(map);
    }
    int len = menuItems.size();
    String[] abc = new String[len]; // array to hold all the names which then will be in the drop-down text view
    for(int i=0;i<len;i++){
        abc[i]=(menuItems.get(i)).get(KEY_NAME);
    }
    String[] a={"abc","bcd"}; //ignore, made for testing

    AutoCompleteTextView textView = (AutoCompleteTextView)     findViewById(R.id.autoCompleteTextViewCourses);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.select_dialog_item, abc);

        textView.setThreshold(1);

        textView.setAdapter(adapter);
        }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.browse_courses, menu);
    return true;
}

}

这是将调用方法的文件。

这是解析器文件:

package com.example.selptimetableproject.ivo.dimitrov;

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

}

我不确定它的android虚拟设备是否无法下载XML文件或其他内容。

1 个答案:

答案 0 :(得分:0)

在Android中解析xml的最佳建议方法是使用xmlPullParser而不是DOM