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));
Related
I have a problem in DOM parsing Arabic letters, I got weird characters. I've tried changing to different encoding but I couldn't.
the full code is on this link: http://test11.host56.com/parser.java
public Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
Reader reader = new InputStreamReader(new ByteArrayInputStream(
xml.getBytes("UTF-8")));
InputSource is = new InputSource(reader);
DocumentBuilder db = dbf.newDocumentBuilder();
//InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
return doc;
}
}
my xml file
<?xml version="1.0" encoding="UTF-8"?>
<music>
<song>
<id>1</id>
<title>اهلا وسهلا</title>
<artist>بكم</artist>
<duration>4:47</duration>
<thumb_url>http://wtever.png</thumb_url>
</song>
</music>
You already have the xml as String, so unless that string already contains the odd characters (that is, it has been read in with the wrong encoding), you can avoid encoding madness here by using a StringReader instead; e.g. instead of:
Reader reader = new InputStreamReader(new ByteArrayInputStream(
xml.getBytes("UTF-8")));
use:
Reader reader = new StringReader(xml);
Edit: now that I see more of the code, it seems the encoding issue already happend before the XML is parsed, because that part contains:
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
The javadoc for the EntityUtils.toString says:
The content is converted using the character set from the entity (if any), failing that, "ISO-8859-1" is used.
It seems the server does not send the proper encoding information with the entity, and then the HttpUtils uses a default, which is not UTF-8.
Fix: use the variant that takes an explicit default encoding:
xml = EntityUtils.toString(httpEntity, "utf-8");
Here I assume the server sends UTF-8. If the server uses a different encoding, that one should be set instead of UTF-8. (However as the XML also declares encoding="UTF-8" I thought this is the case.) If the encoding the server uses is not known, then you can only resort to wild guessing and are out of luck, sorry.
If the XML contains Unicode characters such as Arabic or Persian letters, StringReader would make an exception. In these cases, pass the InputStream straightly to the Document object.
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.
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 wold like to save the given webservice url as xml file for offline sax parsing.
In Online i am using SAX Parser to parse the given url .
URL sourceUrl = new URL("http://www.example.com/mobile/eventinfo.php?id=20);
InputSource inputSource = new InputSource(sourceUrl.openStream());
inputSource.setEncoding("ISO-8859-1");
For that I am getting the inputsourse from url as above and now I want to save that inputsourse as .xml file for offline parsing.
Here User has to load the application for very first time in online. And inside the application we are providing offline facilities. If user sets the app to offline the inputsourse has to save the xml file in local memory.
If the user starts the application in offline the application has to parse the data from saved xml file.
If the user is starts the application online the data has to parse from the url.
Can any one help me out here or share the knowledge
I am generating the xml file like the following code
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.connect();
int responseCode = connection.getResponseCode();
if(responseCode == 200){
InputStream inputStream = connection.getInputStream();
int size = connection.getContentLength();
FileOutputStream fileOutputStream = new FileOutputStream(new File(getCacheDir(),filename));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String ch = null;
while((ch = bufferedReader.readLine()) != null){
fileOutputStream.write(ch.getBytes());
}
}else {
}
}
but its raising an Exception as NetworkonMainThreadException at
connection.connect();
thanks in advance.
I think for the first time you generate the file (contains ur xml) in sdcard,and every time check if that file exists in sdcard then parse same otherwise load data from url and generate xml file.
Hope u get me what i say
Respected All,
I have to read XML file, for that I use SAXParser and DefaultHandler using method characters(char[] ch, int start, int length) but it gives output with some extra characters such as [] in place of '#13'. someone told me that if I read that string in UTF-8 format then it will remove that all the extra characters. Is it true that I have to read it in UTF-8 format if yes then how I can read it.
Thank You
(Vikram Kadam)
I use this to parse with the SAXparser :
URL url = new URL(urlToParse);
SAXParserFactory spf = SAXParserFactory.newInstance();
// here we get our SAX parser
SAXParser sp = spf.newSAXParser();
// we fuse it to a XML reader
XMLReader xr = sp.getXMLReader();
DefaultHandler handlerContact = new DefaultHandler();
// we give it a handler to manage the various events
xr.setContentHandler(handlerContact);
// and finally we open the stream to the url
InputStream oS = url.openStream();
// and parse it
xr.parse(new InputSource(new InputStreamReader(oS, Charset.forName("utf-8"))));
// to retrieve the list of contacts created by the handler
result = handlerContact.getEntries();
// don't forget to close the resource
oS.close();
I never had any trouble as long as the initial file you are parsing is properly encoded in UTF-8. Check if it is, because sometimes, when you use default configuration of your computer, default is not UTF-8 but ANSI or ISO-8859-1