从网站解析xml

时间:2013-09-08 15:04:55

标签: java android xml-parsing

我有一个位于

的xml文件

http://androtrends.hostingsiteforfree.com/direct.xml

我正在尝试解析这个xml文件,以便在我的程序中使用它,但每次程序强制关闭虽然它没有错误。我是java新手,请帮忙!

以下是我在XMLParser.java中使用的代码

public class XMLParser {


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;
}
//Parsing XML content and getting DOM element
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 DOM
        return doc;
}

//Getting each xml child element value by passing element node name


public String getValue(Element item, String str) {
    NodeList n = ((Document) item).getElementsByTagName(str);
    return this.getElementValue(n.item(0));
} 
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 "";
  } 

}

Channel.java 的代码是

public class Channel extends ListActivity{

String selectedmode, channelName, channelLink;

Intent urlIntent;
    // All static variables

static final String DirectURL = "http://androtrends.hostingsiteforfree.com/direct.xml";

static final String FlashURL="http://androtrends.hostingsiteforfree.com/direct.xml";

// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_Channel = "channel";
static final String KEY_Link = "link";
String xml;
Toast toast;
ArrayList<HashMap<String, String>> menuItems;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.channels);
    selectedmode=getIntent().getExtras().getString("key");
    urlIntent=new Intent(Intent.ACTION_VIEW);
    Toast.makeText(this, "Wait 60 secs to load the stream...", Toast.LENGTH_LONG).show();
    updatechannels();

    ListView lv=getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // TODO Auto-generated method stub
            channelName= ((TextView) view.findViewById(R.id.channelName)).getText().toString();
            channelLink= ((TextView) view.findViewById(R.id.channelLink)).getText().toString();
            urlIntent.setData(Uri.parse(channelLink));
            toast.show();
            startActivity(urlIntent);
        }
    });
}

    private void updatechannels() {
    // TODO Auto-generated method stub
     menuItems = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    if (selectedmode.equalsIgnoreCase("direct"))
    {
         xml = parser.getXmlFromUrl(DirectURL); // getting XML
    }else
    {
         xml = parser.getXmlFromUrl(FlashURL);
    }
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    // looping through all item nodes <item>
    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_Channel, parser.getValue(e, KEY_Channel));
        map.put(KEY_Link, parser.getValue(e, KEY_Link));


        // adding HashList to ArrayList
        menuItems.add(map);
    }

    // Adding menuItems to ListView
    ListAdapter adapter = new SimpleAdapter(this, menuItems,
            R.layout.list_item,
            new String[] {  KEY_Channel, KEY_Link }, new int[] {
                    R.id.channelName, R.id.channelLink });

    setListAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}

1 个答案:

答案 0 :(得分:0)

试试这个..

    import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

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.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class NetActivity extends Activity {

    String url = "http://androtrends.hostingsiteforfree.com/direct.xml";


    // Progress dialog
    ProgressDialog pDialog;

    ArrayList<String> title;
    ArrayList<String> description;  

    ItemAdapter adapter1;

    ListView list;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net);

        list = (ListView) findViewById(R.id.list);
        title = new ArrayList<String>();
        description = new ArrayList<String>();          

         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
             new XmlParsing(url).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
         else
             new XmlParsing(url).execute(new String[]{null});   

    }

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

    public class XmlParsing extends AsyncTask<String, Void, String> {

        // variables passed in:
        String urls;
        //  constructor
        public XmlParsing(String urls) {
            this.urls = urls;
        }

        @Override
        protected void onPreExecute() {
            pDialog = ProgressDialog.show(NetActivity.this, "Fetching Details..", "Please wait...", true);
        }


        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            URL url;
            try {

                url = new URL(urls);
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(new InputSource(url.openStream()));

                doc.getDocumentElement().normalize();

                NodeList nodeList = doc.getElementsByTagName("item");

                for (int i = 0; i < nodeList.getLength(); i++) {

                    Node node = nodeList.item(i);       

                    Element fstElmnt = (Element) node;
                    NodeList nameList = fstElmnt.getElementsByTagName("channel");
                    Element nameElement = (Element) nameList.item(0);
                    nameList = nameElement.getChildNodes();
                    title.add(""+ ((Node) nameList.item(0)).getNodeValue());

                    System.out.println("channel : "+((Node) nameList.item(0)).getNodeValue());


                    Element fstElmnt1 = (Element) node;
                    NodeList nameList1 = fstElmnt1.getElementsByTagName("link");
                    Element nameElement1 = (Element) nameList1.item(0);
                    nameList1 = nameElement1.getChildNodes();
                    description.add(""+ ((Node) nameList1.item(0)).getNodeValue());

                    System.out.println("link : "+ ((Node) nameList1.item(0)).getNodeValue());           


                }

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // Now we have your JSONObject, play around with it.
            if (pDialog.isShowing())
                pDialog.dismiss();
            String value = result;

           // Log.v("URL  Res- - - -", ""+value);

            adapter1 = new ItemAdapter(this);
            list.setAdapter(adapter1);

        }

    }


class ItemAdapter extends BaseAdapter {

        final LayoutInflater mInflater;

        private class ViewHolder {
            public TextView title_text;
            public TextView des_text;
        }

        public ItemAdapter(XmlParsing xmlParsing) {
            // TODO Auto-generated constructor stub
            super();
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
        }

        //@Override
        public int getCount() {
            return title.size();
        }

        //@Override
        public Object getItem(int position) {
            return position;
        }

        //@Override
        public long getItemId(int position) {
            return position;
        }

        //@Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = convertView;
            final ViewHolder holder;
            if (convertView == null) {
                view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
                holder = new ViewHolder();
                holder.title_text = (TextView) view.findViewById(R.id.title_text);
                holder.des_text = (TextView) view.findViewById(R.id.des_text);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

            holder.title_text.setText(""+title.get(position));      

            holder.des_text.setText(""+description.get(position));

        return view;
        }
    }
}