Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

very simple question which I don't know the answer

 
Ehsan shin
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I am new in using SAX and I am trying to use it to read a XML file.
here is my SaxHandler Class which extends DefaultHandler code:

private final class SaxHandlerC extends DefaultHandler {

public void startElement(String uri, String localName,
String qName, Attributes attrs) throws SAXException {
if (qName.equals("S")) {
if (attrs.getValue("s_id").toString().equals(candidateSenId)) {
correctTag = true;
} else {
correctTag = false;
}
}
}

public void characters(char ch[], int start, int length)
throws SAXException {
if (correctTag) {
candidateText = new String(ch, start, length);
correctTag = false;
}

}

public void endElement(String uri, String localName,
String qName)
throws SAXException {

if (qName.equals("S")) {
correctTag = false;
}
}
}


here is my problem: i am reading xml file, everything work fine, but in some cases like this, the characters method is not working correct:
input is:

<S s_id="12">
Nicolaisen said that the SEC investigation of Fannie Mae was continuing.
</S>

but output is:
"Nicolaisen said that the SEC investigation of"

what is the problem? it doesn't make any sense for me.

i would appreciate it if you help me.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A common trap.

The characters() method is NOT guaranteed to get the full text - it can return as little as a single character because it can only work with the current buffer. Therefore your characters method needs to accumulate text - say in a StringBuilder - until the endElement call.

Bill
 
Ehsan shin
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much.

I used StringBuffer, and now it is working fine.

William Brogden wrote:A common trap.

The characters() method is NOT guaranteed to get the full text - it can return as little as a single character because it can only work with the current buffer. Therefore your characters method needs to accumulate text - say in a StringBuilder - until the endElement call.

Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic