I'm using a WEB service which return XML format but with < and > instead of "<" and ">".
Now I dont know how to parse it?
I tried the standard SAX parser:
if (entity != null && responseCode==200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
BufferedReader rd = null;
rd = new BufferedReader(new InputStreamReader(instream));
InputSource is=new InputSource(rd);
WebServiceRespondParser parser=new WebServiceRespondParser(category);
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser sp=factory.newSAXParser();
XMLReader reader=sp.getXMLReader();
reader.setContentHandler(parser);
reader.parse(is);
markers=parser.getMarkers();
}
WEB service:
http://gisn.tel-aviv.gov.il/ws_iriya_zmina/wsgis.asmx/GetData4TargetLayersFromAddress?Format=xml&TargetIriaLayerIDs=659&Radiuses=2000&Rechov=798&Bayit=3&Knisa=
I read few similar question, but most are in different languages, or doesn't have answer.
That XML is encoded because it's inside the tag. What you need to do is to first parse the original XML, then get the value from the tag. This will get you the proper XML that you can now parse as usual.
Related
I am transitioning to OKHttp and i am using SAXParser in my project. How can i parse the OKHttp response to SAXParser? or how else can I parse XML using the library.
initially this was how I was doing it:
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
SAXParserFactory factory1 = SAXParserFactory.newInstance();
SAXParser parser = factory1.newSAXParser();
FormHandler handler = new FormHandler();
parser.parse(inputStream, handler);
But with OKHTTP, how can i pass Response response = client.newCall(request).execute() to the XML parser?
You might try this :
// 1. get a http response
Response response = client.newCall(request).execute();
// 2. construct a string from the response
String xmlstring = response.body().string();
// 3. construct an InputSource from the string
InputSource inputSource = new InputSource(new StringReader(xmlstring));
// 4. start parsing with SAXParser and handler object
// ( both must have been created before )
parser.parse(inputSource,handler);
PS : in your question you mention XMLPullParser, in your code you're actually using a SAXParser. However, if you have the xml string on your hands, you should do fine with both ways.
I parse an XML document from a HTTPResponse.
Previously I initiated the parser with a String object created from the InputStream.
When I changed the setup so the inputStream isused directly in the parser I get OutOfMemory Exceptions.
The strange thing is that parsing the String worked without problems before, so I wonder why the InputStream should need more memory.
Previous code:
final byte[] encodedResponseBytes = IOUtils.toByteArray(httpResponse
.getEntity().getContent());
String message = new String(encodedResponseBytes);
parser.setInput(new StringReader(message));
New code:
InputStream stream = httpResponse
.getEntity().getContent();
parser.setInput(stream, null);
By changing the code I don't have a problem anymore:
InputStream stream = request.getResponseStream();
reader = new InputStreamReader(stream);
this.xmlParser.setInput(reader);
I'm getting back names of (Foursquare) venues from a server call where the names of the venues returned can be in English or non-English.
Assume the venue name is in a JSON object as follows:
{...
"name":"venue name which can be in any language"
...}
I'm creating a JSONObject from this response and then pulling out the name of the venue as follows:
String name = jsonObject.getString("name");
Lastly, I'm setting the TextView's text to show the name of the venue as follows:
myTextView.setText(name);
I'm finding however for Arabic names that where the Arabic characters are joined in the original JSON object (as they should be), the characters that show in the app (i.e. in the TextView) are disjoint. (I'm not too familiar with other languages so can't really tell if they're showing incorrectly too.)
Is there something additional I should be doing to pull out non-English names correctly from the JSON object and setting it as the text of a TextView, or is it down to the phone to decide how the text will be displayed?
Edit: I've tried parsing the server response (as suggested by #bbedward) explicitly specifying the content encoding as UTF-8 as follows...
HttpEntity httpEntity = httpResponse.getEntity();
String responseMessage = EntityUtils.toString(myHttpEntity, "UTF-8");
JSONObject jsonObject = new JSONObject(responseMessage);
... but still no joy. (Arabic characters appear, as before, disjoint in words where they should be joint up.) Could it be a phone thing or is there something extra needing to be done myself to get the words/characters to show proper in non-English languages? Perhaps the server needs to explicitly specify a "Content-Type" header with value "UTF-8"?
I'm going to answer anyway, I'm guessing you aren't getting your json in UTF-8 as i had a similar problem, I believe json won't come any other way.
Complete Example
The only things to concern yourself with this is setting the encoding for the InputStreamReader and creating the JSONObject
private DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://myjsonurl.com/search?type=json");
// Depending on your web service
httppost.setHeader("Content-type", "application/json");
try
{
String result = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
JSONObject myJObject = new JSONObject(sb.toString();
}
catch (Exception e)
{
}
finally
{
try{if(inputStream != null)inputStream.close();}catch(Exception none){}
}
add this line when you connect to mysql:
mysql_set_charset('utf8', $con);
ex:
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_set_charset('utf8', $con);
mysql_select_db(DB_DATABASE);
I am getting this error while trying to Parse the Xml response from the Web Service by SAX Parser in Android.
ERROR in LogCat :- " Response =====> org.xml.sax.InputSource#43b8e230 "
I got to know that I need to convert the response in String may be by toString() Method, but the problem is I don't know how to do that as I had tried all the possible ways I knew for conversion but nothing happened.
In InputSource I am passing the url:-
URL url = new URL("http://www.google.com/ig/api?weather=Ahmedabad");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xmlr = sp.getXMLReader();
DemoHandler myDemoHandler = new DemoHandler();
xmlr.setContentHandler(myDemoHandler);
xmlr.parse(new InputSource(url.openStream()));
Log.e(TAG, "Condition");
System.out.println("Response ====> " + new InputSource(url.openStream().toString()));
ParsedDemoData parsedDemoData = myDemoHandler.getParsedData();
Everything is fine but the response I am getting needs to be converted into String which I don't know how to do.
Can anyone please help in this.
Thanks,
david
To parse an InputStream you don't have to convert it into a string you can directly read its elements and attributes using Parsers available on Android. You can refer the following links to do the same
http://www.ibm.com/developerworks/opensource/library/x-android/index.html
http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html
How ever if you are looking for a code that converts Input Stream to string something like this will work
public String convertStreamToString(InputStream is) throws IOException {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
And this should print the stream for you
System.out.println("Response ====> " + convertStreamToString(url.openStream()));
I just read some tutorials in order to parse a xml feed from the web and turn them into a Listview:
URL file = new URL("http://..../file.xml");
SAXParserFactory fabrique = SAXParserFactory.newInstance();
SAXParser parseur = fabrique.newSAXParser();
XMLReader xr = parseur.getXMLReader();
ReglageParseur gestionnaire = new ReglageParseur();
xr.setContentHandler(gestionnaire);
xr.parse(new InputSource(file.openStream()));
Everything is fine and I am able to parse xml.
My second step is to store the xml file from web into a xml file on the phone and only update it when user ask it. ( In fact, this xml file should not change or maybe once every 6 month, so I don't want to download it each time.)
So, what I did is to store the file on the phone and update it on user demand.
And I can read it by doing:
fIn = openFileInput("fichier.xml");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[255];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
So, for now, everything seem fine and I am nearly happy.
The problem is now when I want to parse the new file on the phone:
xr.parse(InputSource);
I need an InputSource as parameter.
So my question is:
How can I turn my file in the phone into a InputSource?
I succeed to have a InputStreamReader or a String but would like to convert that into InputSource.
Thank a lot for any precious help
Well, I don't know what constructors are available on the Android version, but the J2SE InputSource class has a constructor with a Reader parameter. Have you tried that?
Alternatively, why not just construct an InputSource directly from the InputStream? I assume fIn is a FileInputStream? Why not just call:
InputSource input = new InputSource(fIn);
?
the best suitable line for me to convert string to InputSource is :
String myStringObject = "Hello this is string object to convert in InputSource";
InputSource inSource = new InputSource(new StringReader(myStringObject));