I am doing a program to parse a XML file from http. And the XML have some space at the front of root tag.
So, I need to trim the XML before parse it.
Here is the method I written,
private String trimXML(InputStream inputStream){
Writer writer = null;
try{
writer = new StringWriter();
char[] buffer = new char[Constants.BUFFER_SIZE];
try {
Reader reader = null;
try {
reader = new BufferedRea开发者_StackOverflow中文版der(new InputStreamReader(inputStream, "UTF-8"));
int n = 0;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return writer.toString().trim();
}catch(NullPointerException e){
return null;
}
}
Now I am facing a big problem is after I request the XML few times, the out of memory error is get...
Could anyone give me some suggestion to solve it?
Why? XML parser's don't care about white space. And if you are receiving an XML document that doesn't parse, the solution is to fix the sender, not kludge something up at the receiver. That way everybody is wrong.
You are using StringWriter
, which means you keep on writing the XML file content to the buffer in memory. So, obviously, if the last buffer stays in the memory and not garbage collected yet, you will hit OutOfMemory
.
By the way, I am not understanding how your program is solving your problem. It is merely trimming the whole document. Which means it will clear the white-spaces from the beginning and the end of the document.
My suggestion to you is, you need not worry about the white space and parse the document using StAX or whatever feel appropriate to you. And trim the thing during parsing, if necessary.
However, flushing might help. Thus, a quick fix can be this,
..
..
String str = writer.toString().trim();
writer.flush();
return str;
..
..
NB: white-spaces around XML elements will be ignored by the parser, nonetheless. If you need to trim some attributes/elements values, that's another story.
Can I suggest that perhaps you are trying to solve a problem that has already been solved? Do you need to write the parser yourself?
What I would suggest is to not try and parse the XML yourself, but use a library like the Simple XML library which works on Android. I actualy just wrote a blog post explaining how to include it in one of your projects: you can find that here.
You could advance the InputStream to the first occurrence of '<' using something like:
InputStream inputStream = new BufferedInputStream(YOUR_INPUT_STREAM);
byte[] start = "<".getBytes("UTF-8");
byte[] potentialStart = new byte[1];
inputStream.read(potentialStart);
while(start[0] != potentialStart[0]) {
inputStream.mark(1);
inputStream.read(potentialStart);
}
inputStream.reset();
精彩评论