我正在使用SaxHandler来解析来自第三方应用的日志文件。我的代码:
public class SaxHandler extends DefaultHandler {
private String tempVal;
private String response;
private boolean readResponse;
boolean elementOn;
public SaxHandler() {
readResponse = false;
elementOn = false;
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("method") || qName.equalsIgnoreCase("message")) {
elementOn = true;
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("message")) {
if (readResponse) {
response = tempVal;
readResponse = false;
}
}
if (qName.equalsIgnoreCase("method")) {
if (tempVal.equalsIgnoreCase("postHtml")) {
readResponse = true;
}
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
tempVal = new String(ch, start, length);
elementOn = false;
}
}
public String getLastResponse() {
return response;
}
}
日志文件中的示例记录:
<record>
<date>07.07.2014 16:12:45</date>
<millis>1404735165155</millis>
<sequence>12</sequence>
<logger>logName</logger>
<level>FINER</level>
<class>ru.tsi.maksbm.android.revise.ReviseStartActivity</class>
<method>onStart</method>
<thread>0</thread>
<message>Starting ReviseStartActivity</message>
</record>
Parser正在开始正常解析,但我得到SaxParser没有格式错误。我验证了日志文件,它在以下行失败了:
<message>action=%D0%92%D1%85%D0%BE%D0%B4&j_username=U_USER&password=hash&</message>
出现下一个错误:
"The reference to entity "j_username" must end with the ';' delimiter"
为什么解析器不会将此行识别为单个字符串?