Search code examples
androidxml-parsingxmlhttprequestdomparser

XML parsing : encoding utf-8 & UTF-8


I am trying to parse the values from this LINK, whose xml encoding is like this

<?xml version="1.0" encoding="utf-8"?>

when I tried to get response throws message in logcat as shown

11-19 17:25:13.350: W/System.err(3360): This is not valid URL
11-19 17:25:13.350: W/System.err(3360): java.lang.NullPointerException

When I tried with some other LINK ,whose encoding is like this

<?xml version="1.0" encoding="UTF-8"?> It works fine, I can parse the values.

is xml parsing failing due encoding not being UTF-8,it is utf-8 ??

How should I deal with this. I have done google and am new to XML parsing. This is my first parsing which I am trying to create. Please let me know the way.

updated with code :

public String getXmlFromUrl(String url) {

    String xml = null;

    try {            
        // defaultHttpClient
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);           
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity(); 
        xml = EntityUtils.toString(httpEntity);
        System.out.println("response -- " + xml);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

Solution

  • Straight away it looks like the problem is with Encoding of XML in your response.

    URL url = new URL("http://myurl.com");
    InputSource is = new InputSource(url.openStream());
    is.setEncoding("ISO-8859-1"); // Also Try UTF-8 or UTF-16
    BufferedReader br = new BufferedReader(new InputStreamReader(is.getByteStream()));
    String line,str;
    while((line=br.readLine())!=null)
    {
          str = str + line;
    }
    Log.i(TAG,str);