Java 使用 sax 解析 xml 个文件。上来时无法获取正确的内容&amp

Java use sax to parse xml files. Can't get the correct content when coming up &amp

我在用 sax 解析 xml 文件时遇到一些问题。

Java contenthandler 代码如下所示:

boolean rcontent = false;

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if (qName.equalsIgnoreCase("content")) {
        rcontent = true;
    }
}

@Override
public void characters(char ch[], int start, int length) throws SAXException {
    if (rcontent){
        System.out.println("content: " + new String(ch, start, length));
        rcontent = false;
    }
}

Xml文件内容是这样的:

但输出是:

我想说

不完整。

很可能 characters(...) 被单个 <content> 块调用了多次。试试像

StringBuilder builder;

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if (qName.equalsIgnoreCase("content")) {
        builder = new StringBuilder();
    }
}

@Override
public void characters(char ch[], int start, int length) throws SAXException {
    if (builder != null){
        builder.append(new String(ch, start, length));
    }
}

@Override
public void endElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if (builder != null) {
        System.out.println("Content = " + builder);
        builder = null;
    }
}