您可以使用 sax 解析器,我编写了一小段代码来向您展示如何获取条目中的标题。我没有测试它,但我认为它会帮助你用 sax 解析 XML 文件。
这里的代码:
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxParserContent {
public static void parse(String data) {
SAXParserFactory factory = SAXParserFactory.newInstance();
SaxParserContent.HandlerContent handler = new HandlerContent();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new InputSource(new StringReader(data)), handler);
} catch (Throwable err) {
}
}
public static class HandlerContent extends DefaultHandler {
protected boolean inEntry = true;
protected boolean inTitle = true;
protected String title;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equals("ENTRY")) {
inEntry = true;
}
if (inEntry == true && localName.equals("TITLE")) {
inTitle = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equals("ENTRY")) {
inEntry = false;
}
if (inEntry == true && localName.equals("TITLE")) {
inTitle = false;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (inEntry == true && inTitle == true) {
title = new String(ch);
}
}
public String getTitle() {
return title;
}
}
}
祝你好运 !