title: how to convert html string in java string
body: <p>I'm retrieving an XML from the Google Maps Directions API. <br/>
  The result is something like this:</p>
  
  <pre><code>    &lt;DirectionsResponse&gt;
       &lt;status&gt;OK&lt;/status&gt;
       &lt;route&gt;
        &lt;summary&gt;I-40 W&lt;/summary&gt;
        &lt;leg&gt;
         &lt;step&gt;
          &lt;travel_mode&gt;DRIVING&lt;/travel_mode&gt;
          &lt;start_location&gt;
           &lt;lat&gt;41.8507300&lt;/lat&gt;
           &lt;lng&gt;-87.6512600&lt;/lng&gt;
          &lt;/start_location&gt;
          &lt;end_location&gt;
           &lt;lat&gt;41.8525800&lt;/lat&gt;
           &lt;lng&gt;-87.6514100&lt;/lng&gt;
          &lt;/end_location&gt;
          &lt;polyline&gt;
           &lt;points&gt;a~l~Fjk~uOwHJy@P&lt;/points&gt;
          &lt;/polyline&gt;
          &lt;duration&gt;
           &lt;value&gt;19&lt;/value&gt;
           &lt;text&gt;1 min&lt;/text&gt;
          &lt;/duration&gt;
          &lt;html_instructions&gt;Head &lt;b&gt;north&lt;/b&gt; on &lt;b&gt;S Morgan St&lt;/b&gt; toward &lt;b&gt;W Cermak Rd&lt;/b&gt;&lt;/html_instructions&gt;
          &lt;distance&gt;
           &lt;value&gt;207&lt;/value&gt;
           &lt;text&gt;0.1 mi&lt;/text&gt;
          &lt;/distance&gt;
         &lt;/step&gt;
         ...
         ... additional steps of this leg
        ...
        ... additional legs of this route
         &lt;duration&gt;
          &lt;value&gt;74384&lt;/value&gt;
          &lt;text&gt;20 hours 40 mins&lt;/text&gt;
         &lt;/duration&gt;
         &lt;distance&gt;
          &lt;value&gt;2137146&lt;/value&gt;
          &lt;text&gt;1,328 mi&lt;/text&gt;
         &lt;/distance&gt;
         &lt;start_location&gt;
          &lt;lat&gt;35.4675602&lt;/lat&gt;
          &lt;lng&gt;-97.5164276&lt;/lng&gt;
         &lt;/start_location&gt;
         &lt;end_location&gt;
          &lt;lat&gt;34.0522342&lt;/lat&gt;
          &lt;lng&gt;-118.2436849&lt;/lng&gt;
         &lt;/end_location&gt;
         &lt;start_address&gt;Oklahoma City, OK, USA&lt;/start_address&gt;
         &lt;end_address&gt;Los Angeles, CA, USA&lt;/end_address&gt;
        &lt;copyrights&gt;Map data ©2010 Google, Sanborn&lt;/copyrights&gt;
        &lt;overview_polyline&gt;
         &lt;points&gt;a~l~Fjk~uOnzh@vlbBtc~@tsE`vnApw{A`dw@~w\|tNtqf@l{Yd_Fblh@rxo@b}@xxSfytAblk@xxaBeJxlcBb~t@zbh@jc|Bx}C`rv@rw|@rlhA~dVzeo@vrSnc}Axf]fjz@xfFbw~@dz{A~d{A|zOxbrBbdUvpo@`cFp~xBc`Hk@nurDznmFfwMbwz@bbl@lq~@loPpxq@bw_@v|{CbtY~jGqeMb{iF|n\~mbDzeVh_Wr|Efc\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg@|kHntyArpb@bijCk_Kv~eGyqTj_|@`uV`k|DcsNdwxAott@r}q@_gc@nu`CnvHx`k@dse@j|p@zpiAp|gEicy@`omFvaErfo@igQxnlApqGze~AsyRzrjAb__@ftyB}pIlo_BflmA~yQftNboWzoAlzp@mz`@|}_@fda@jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC&lt;/points&gt;
        &lt;/overview_polyline&gt;
        &lt;optimized_waypoint_index&gt;0&lt;/optimized_waypoint_index&gt;
        &lt;optimized_waypoint_index&gt;1&lt;/optimized_waypoint_index&gt;
        &lt;bounds&gt;
         &lt;southwest&gt;
          &lt;lat&gt;34.0523600&lt;/lat&gt;
          &lt;lng&gt;-118.2435600&lt;/lng&gt;
         &lt;/southwest&gt;
         &lt;northeast&gt;
          &lt;lat&gt;41.8781100&lt;/lat&gt;
          &lt;lng&gt;-87.6297900&lt;/lng&gt;
         &lt;/northeast&gt;
        &lt;/bounds&gt;
       &lt;/route&gt;
      &lt;/DirectionsResponse&gt;
  </code></pre>
  
  <p>I try to print the value of the tag , but it shows also the <code>&lt;b&gt;</code> or the <code>&lt;div&gt;</code>.  <br/>
  Thus I try to use the class <code>StringEscapeUtils</code> like this: <br/></p>
  
  <pre><code>StringEscapeUtils.escapeHtml4(KEY_HTML_INSTRUCTIONS);
  </code></pre>
  
  <p>but it doesn't work. <br/></p>
  
  <p>I use this XML Parser:</p>
  
  <pre><code>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 {
  
  
      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;
      }
  
      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;
      }
  
      public String getValue(Element item, String str) {      
          NodeList n = 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 "";
      }
  }
  </code></pre>
  
  <p>And here is the activity that shows the information taken from the XML:</p>
  
  <pre><code>import maps.XMLParser;
  
  import org.apache.commons.lang3.StringEscapeUtils;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.NodeList;
  
  import android.app.ListActivity;
  import android.app.ProgressDialog;
  import android.content.Intent;
  import android.os.AsyncTask;
  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 DirectionsActivity extends ListActivity {
  
      String url = "";
      XMLParser parser;
      String xml = "";
      ArrayList&lt;HashMap&lt;String, String&gt;&gt; menuItems;
  
      // All static variables
      static final String KEY_STEP = "step"; // parent node
      static final String KEY_HTML_INSTRUCTIONS = "html_instructions";
      static final String KEY_DURATION = "duration";
      static final String KEY_DISTANCE = "distance";
  
  
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
  
          Intent intent = this.getIntent();
  
          url = intent.getExtras().getString("url");
          System.out.println("---------------" + url);
  
          menuItems = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();
  
          parser = new XMLParser();
  
          DownloadTask downloadTask = new DownloadTask();
  
          // Start downloading json data from Google Directions API
          downloadTask.execute(url);
  
          // selecting single ListView item
          ListView lv = getListView();        
  
          // listening to single listitem click
          lv.setOnItemClickListener(new OnItemClickListener() {
  
             @Override
             public void onItemClick(AdapterView&lt;?&gt; parent, View view,
                     int position, long id) {
                 // getting values from selected ListItem
                 String name = ((TextView) view.findViewById(R.id.instruction)).getText().toString();
                 // String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
                 // String description = ((TextView) view.findViewById(R.id.description)).getText().toString();
  
                 // Starting new intent
                 Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                 in.putExtra(KEY_HTML_INSTRUCTIONS, name);
                 // in.putExtra(KEY_COST, cost);
                 // in.putExtra(KEY_DESC, description);
                 startActivity(in);
  
             }
         });
      }
  
      /** A class to download data from Google Directions URL */
      private class DownloadTask extends AsyncTask&lt;String, Void, String&gt;{
  
          ListAdapter adapter;
          private ProgressDialog pd;
  
          @Override
          protected void onPreExecute() {
                   pd = new ProgressDialog(DirectionsActivity.this);
                   pd.setTitle("Processing...");
                   pd.setMessage("Calcolo direzione in corso dalla posizione corrente...");
                   pd.setCancelable(false);
                   pd.setIndeterminate(true);
                   pd.show();
          }
  
          // Downloading data in non-ui thread
          @Override
          protected String doInBackground(String... url) {
  
              // For storing data from web service
              String data = "";
  
              try{
                  // Fetching the data from web service
                  data = parser.getXmlFromUrl(url[0]);
              }catch(Exception e){
                  Log.d("Background Task",e.toString());
              }
              return data;
          }
  
          // Executes in UI thread, after the execution of
          // doInBackground()
          @Override
          protected void onPostExecute(String result) {
              super.onPostExecute(result); 
  
              Document doc = parser.getDomElement(result); // getting DOM element
  
              NodeList nl = doc.getElementsByTagName(KEY_STEP);
              // looping through all item nodes &lt;item&gt;
              for (int i = 0; i &lt; nl.getLength(); i++) {
                  // creating new HashMap
                  HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
                  Element e = (Element) nl.item(i);
                  // adding each child node to HashMap key =&gt; value
                  String escapeKeyHtmlInstructions = StringEscapeUtils.escapeXml(KEY_HTML_INSTRUCTIONS);
                  // KEY_HTML_INSTRUCTIONS.replaceAll("\\&lt;.*?&gt;", "");
                  map.put(KEY_HTML_INSTRUCTIONS, parser.getValue(e, escapeKeyHtmlInstructions));
                  // map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
                  // map.put(KEY_DISTANCE, "Rs." + parser.getValue(e, KEY_DISTANCE));
                  // map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
  
                  // adding HashList to ArrayList
                  menuItems.add(map);
              }
  
              // Adding menuItems to ListView
              adapter = new SimpleAdapter(DirectionsActivity.this, menuItems,R.layout.list_item,
                      new String[] { KEY_HTML_INSTRUCTIONS}, new int[] {
                              R.id.instruction});
  
              setListAdapter(adapter);
  
              pd.dismiss();
          }
      }
  
  }
  </code></pre>
  
  <p>How can I fix that? Is there other libraries I can use?</p>