2

需要帮助弄清楚为什么我的字符串缓冲区在用覆盖的 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) 期望返回一个字符串(记住),但记住始终为空。

4

1 回答 1

1

您需要返回dh.remember而不是remember

或者

打电话sax.parse( is , this );而不是sax.parse( is , dh );

于 2012-04-27T20:22:58.513 回答