需要帮助弄清楚为什么我的字符串缓冲区在用覆盖的 SAX 回调方法更新后为空。我的代码:
public class SAXXMLParser extends DefaultHandler
{
SAXParserFactory factory;
SAXXMLParser dh;
SAXParser sax;
StringBuffer accumulator;
String remember = "";
public String saxParse( String msgToParse, String uriPathExpression )
throws SAXException, IOException, ParserConfigurationException
{
System.out.println( "saxParse" );
factory = SAXParserFactory.newInstance();
sax = factory.newSAXParser();
dh = new SAXXMLParser();
InputStream is = new ByteArrayInputStream( msgToParse.getBytes() );
sax.parse( is , dh );
System.err.println( remember );
return remember;
}
public void startElement( String uri, String localName, String elementName, Attributes attrs )
{
accumulator.setLength(0);
}
public void endElement( String uri, String name, String qName )
{
System.out.println( qName );
if( qName.equalsIgnoreCase( "my element" ) )
{
remember = accumulator.toString();
}
}
public void characters( char[] ch, int start, int len )
{
accumulator.append( ch, start, len );
}
public void startDocument()
{
accumulator = new StringBuffer();
}
}
在另一个类中,我调用 SAXXMLParser.saxParse(string, string) 期望返回一个字符串(记住),但记住始终为空。