1

The problem is, when i try to get value from xml below

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

and My application code below 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);
     }
    }

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

but while getting value of <description> tag.. there is HTML tags... So on "<" is returned as value.. in rest other its perfectly fine. How can i get all the value, or in best case how can i get values excluding HTML tags..

WAiting for help, Thanks in advance

user98239820
  • 1,411
  • 2
  • 16
  • 30
  • change to JSONRepresentation of the downloaded XML content and use it for data manipulation. - Check the link http://stackoverflow.com/questions/7724263/how-to-convert-xml-to-json-in-java – Lalith B Aug 13 '12 at 11:30
  • Need to work in XML itself.. Cant go under conversion process.. – user98239820 Aug 13 '12 at 11:36
  • If you get HTML content as a response in your tag then the fix should be done on the server end to convert it all to properly formatted data, Or load the whole content of description in any WebView. – Lalith B Aug 13 '12 at 11:43
  • Read this for solution to your problem - http://stackoverflow.com/questions/240546/removing-html-from-a-java-string – Lalith B Aug 13 '12 at 11:46
  • Use a StringBuffer instead of a String – eoghanm Aug 13 '12 at 12:16

1 Answers1

0

Thanks everyone for your support.. But i solved it in different way...

I did some changes in XMLParser.java file...

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

But still i have a problem. If there is picture in xml, that is returned as "obj", which i dont want to see..

user98239820
  • 1,411
  • 2
  • 16
  • 30