1

问题是,当我尝试从下面的 xml 中获取价值时

<item>
 <title>The Return of Toastmasters</title>
 <link>http://www.younginnovations.com.np/blogs/anjan/2012/06/return-toastmasters</link>
 <description>&lt;p&gt;As the title implies, it was the &lt;strong&gt;return of the Toastmasters&lt;/strong&gt; at YoungInnovations on Thursday, May 24, 2012. I said &amp;quot;return&amp;quot; because Toastmasters saw a long gap of more than 3 months. Why the delay? Well, we shifted to a new office building and it took us some time to adjust properly into the new place. However, we&#039;re all glad that we continued with the event even after a long gap. And rightfully so, the MC for the day, Bimal Maharjan, announced the theme for the meeting: Return.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://www.younginnovations.com.np/blogs/anjan/2012/06/return-toastmasters&quot; target=&quot;_blank&quot;&gt;read more&lt;/a&gt;&lt;/p&gt;</description>
 <comments>http://www.younginnovations.com.np/blogs/anjan/2012/06/return-toastmasters#comments</comments>
 <category domain="http://www.younginnovations.com.np/category/tags/toastmasters">Toastmasters</category>
 <pubDate>Mon, 04 Jun 2012 07:28:33 +0000</pubDate>
 <dc:creator>anjan</dc:creator>
 <guid isPermaLink="false">151 at http://www.younginnovations.com.np</guid>
</item>

和我在 News.java 下面的应用程序代码

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.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class News extends ListActivity {

    static final String URL = "http://www.younginnovations.com.np/blog/feed";
    static final String KEY_ITEM = "item"; 
    static final String KEY_TITLE = "title";
    static final String KEY_DESC = "description";
    static final String KEY_DATE = "pubDate";
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.news);

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

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); 
        Document doc = parser.getDomElement(xml); 

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);

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

            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);

            Log.e("Element", e.toString());
            System.out.println(e);

            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
            map.put(KEY_DESC, parser.getValue(e, KEY_DESC));


            menuItems.add(map);
        }


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

        setListAdapter(adapter);
     }
    }

和 XMLParse.java

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

但是在获取<description>标签的值时..有HTML标签...所以“<”作为值返回..在其他方面完全没问题。我怎样才能得到所有的价值,或者在最好的情况下,我怎样才能得到不包括 HTML 标签的值..

等待帮助,在此先感谢

4

1 回答 1

0

感谢大家的支持..但我以不同的方式解决了它......

我在 XMLParser.java 文件中做了一些更改...

 public final String getElementValue( Node elem ) {
     Node child;
     String returnValue = "" ;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                 if( child.getNodeType() == Node.TEXT_NODE ){
                   // String returnValue =  child.getNodeValue();
                   returnValue +=  child.getTextContent();   
                 }

             }
         //   Log.e("ReturnValue", Html.fromHtml(returnValue).toString());
             return Html.fromHtml(returnValue).toString();
         }
     }
     return "";
 }

但我还是有问题。如果xml中有图片,则返回为“obj”,我不想看到..

于 2012-08-15T06:36:55.660 回答