在Cdata描述标签Dom解析中解析Imagelink

时间:2013-02-27 10:37:28

标签: android xml parsing dom

我想检索描述标签内的图片链接,我的标签全部正常工作,这里是描述标签的示例:

[http://news.instaforex.com/analytics/rss][1]

我想检索图片链接或显示图片。我的问题是如何根据我的下面的代码?

mainactivity





    public class AndroidXMLParsingActivity extends ListActivity {

    // All static variables
    static final String URL = "http://news.instaforex.com/analytics/rss";


    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_TITLE = "title";
    static final String KEY_PUBDATE = "pubDate";
    static final String KEY_DESCRIPTION = "description";



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



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

        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 <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, Spanned> map = new HashMap<String, Spanned>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
            map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
            String description = parser.getValue(e, KEY_DESCRIPTION);;
            int index = description.indexOf("The material has been provided by InstaForex Company", 0);
            description = description.substring(0, index-1);
            map.put(KEY_DESCRIPTION, Html.fromHtml(description));



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





        // Adding menuItems to ListView

        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item,
                new String[] { KEY_TITLE, KEY_PUBDATE }, new int[] {
                        R.id.name, R.id.cost }); 



        setListAdapter(adapter);
        ((BaseAdapter) adapter).notifyDataSetChanged();









        // selecting single ListView item
        ListView lv = getListView();






        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                String title = menuItems.get(position).get(KEY_TITLE).toString();
                String pubDate = menuItems.get(position).get(KEY_PUBDATE).toString();
            String description= menuItems.get(position).get(KEY_DESCRIPTION).toString();


        System.out.println("PubDate==>"+pubDate+"\n Description===>"+description);

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(KEY_TITLE, title);
                in.putExtra(KEY_PUBDATE, pubDate);
                in.putExtra(KEY_DESCRIPTION, description);
                startActivity(in);
            }
        });


    }
}

XMLParser的

    package com.androidhive.xmlparsing;

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.text.Html;
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();
        dbf.setCoalescing(true);
        dbf.setNamespaceAware(true);
        if (dbf.isNamespaceAware()==Boolean.TRUE) {
            dbf.setNamespaceAware(Boolean.FALSE);

        }
        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 || child.getNodeType() == Node.CDATA_SECTION_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));
        }




}

0 个答案:

没有答案