我正在使用 SAX Parser 来解析Android应用上RSS源的XML文件,有时解析项目的pubDate还没有完成(不完整的字符)
实施例
Actual PubDate 星期四,2015年4月2日12:23:41 +0000
PubDate解析结果:周四,
以下是我在解析器处理程序中使用的代码:
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("item".equalsIgnoreCase(localName)) {
currentItem = new RssItem(url);
} else if ("title".equalsIgnoreCase(localName)) {
parsingTitle = true;
} else if ("link".equalsIgnoreCase(localName)) {
parsingLink = true;
} else if ("pubDate".equalsIgnoreCase(localName)) {
parsingDate = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("item".equalsIgnoreCase(localName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equalsIgnoreCase(localName)) {
parsingTitle = false;
} else if ("link".equalsIgnoreCase(localName)) {
parsingLink = false;
} else if ("pubDate".equalsIgnoreCase(localName)) {
parsingDate = false;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (parsingTitle) {
if (currentItem != null) {
currentItem.setTitle(new String(ch, start, length));
parsingTitle = false;
}
} else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
} else if (parsingDate) {
if (currentItem != null) {
currentItem.setDate(new String(ch, start, length));
parsingDate = false;
}
}
}
字符丢失非常随机,每次运行应用程序时都会出现在不同的XML项目中。
答案 0 :(得分:0)
您假设每个元素只有一个characters()
个调用。这不是一个安全的假设。通过对characters()
的1次以上调用建立您的字符串,然后将其应用于endElement()
。
或者,更好的是,使用a number of existing RSS parser libraries中的任何一个。