在覆盖的SAX回调方法中更新后,需要帮助弄清楚为什么我的stringbuffer为空。我的代码:
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),期望返回一个字符串(记住),但记住始终为null。
答案 0 :(得分:1)
您需要返回dh.remember
而不是remember
或
致电sax.parse( is , this );
而非sax.parse( is , dh );