To be really correct, you would need to accumulate the value passed in characters, as it may be called more than once per tag.
This can notably happen if you have entities in the text. A tag such as <a>123</a>
is equivalent to <a>123</a>
(49,50,51 are illustrative, but I think these are the right codes for 1,2,3)
So here is an excerpt taken from this question:
private StringBuffer curCharValue = new StringBuffer(1024);
@Override
public void startElement (String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if(qName.equals("author")){
curCharValue.clear();
}
}
@Override
public void characters (char ch[], int start, int length) throws SAXException
{
//already synchronized
curCharValue.append(char, start, length);
}
@Override
public void endElement (String uri, String localName, String qName)
throws SAXException
{
if(qName.equals("author")){
String author = curCharValue.toString();
}
}
To convert from StringBuffer
to int, just use new Integer( curCharValue.toString() )
. Note that there are other methods to convert from String
to Integer
or int
, as pointed out in the comment.