更新时间:2023-11-04 14:16:46
我的猜测是,您将对 characters
的每次调用都视为为 cat
提供完整的文本元素.您应该对处理程序进行编码,以便对 characters
的连续调用累积文本,并且仅在 endElement
事件中捕获它:
My guess is that you are treating each call to characters
as delivering the complete text for a cat
element. You should code your handler so that successive calls to characters
accumulate the text, and you only capture it on the endElement
event:
public class CatHandler extends DefaultHandler {
private StringBuilder chars = new StringBuilder();
public void startElement(String uri, String lName, String qName, Attributes a)
{
final String name = qName == null ? lName : qName;
if ("cat".equals(name)) {
chars.setLength(0);
} else . . .
}
public void endElement(String uri, String lName, String qName) {
final String name = qName == null ? lName : qName;
if ("cat".equals(name)) {
String catName = chars.toString();
// do something with cat name
} else . . .
}
public void characters(char[] ch, int start, int length) {
chars.append(ch, start, length);
}