views:

141

answers:

2

I am parsing xml using the SAXParser and want to know if this is the right way to implement the characters method.

Assume there's a class-level String variable named elementValue and it is initialized to "" in the startElement method.

Here is the characters method:

@Override
public void characters(char[] ch, int start, int length)
{
    String charsToAppend = new String(ch, start, length);
    elementValue = elementValue + charsToAppend;    
}

Is it correct that we need to append to the value we have so far and is the append being done correctly?

Also, why does the characters method give the start index? Won't it be zero every time?

Thanks.

+3  A: 

Yes, you need to append because there is no guarantee that the chunk of data read will contain all of the element text.

The start position is given and needs to be used because the other characters in the array can be junk.

However, you should use a StringBuffer instead, and call its' append() method, like so:

public void characters(char[] ch, int start, int length) {
  yourStringBuffer.append(ch, start, start + length);
}
JRL
Thanks, I'll switch to using a StringBuffer. But out of curiosity, why wouldn't the parser just send a "clean" array instead?
Padawan
The design provides the parser with the ability to read characters into a buffer, and select part of that buffer to be passed to the application via the characters() method. This provides the potential efficiency of not having to produce a new String object which might be discarded by the application.
Paul Clapham
Actually the code for appending to the StringBuffer (or StringBuilder) should be:yourStringBuffer.append(ch, start, length);
Paul Clapham
Paul, thanks for the explanation and correction for the append call.
Padawan
A: 

Thanks Padawan..

Your question it self helped me to fix one bug

sujana