还是sax解析xml的问题?高手请看
现在有个XML文件比较大,但我现在只需要取根节点下的属性的值,不想用dom,因为太大了,加载到内存中比较耗内存,但是我想取道要的属性值后,就退出程序,不要在往下在解析了,如何实现啊
public class DbXmlFile extends DefaultHandler{
public void startElement(String uri, String localName, String tag,
Attributes attribs)
throws SAXParseException {
System.out.println(localName);//这里把所有的element都打印出来了,
if (localName.equals("ROOT")) {
String beginDate = attribs.getValue("beginDate");
String endDate = attribs.getValue("endDate");
this.fileBeginDate=Date.valueOf(beginDate);
this.fileEndDate=Date.valueOf(endDate);
System.out.println(beginDate);
System.out.println(endDate);
//我想在这里就退出,让parser不要再解析下去了,因为我需要的值已经取到,而且下面非长大,可能比较耗时,但是这里打印每次都打出来,如何停止呢
}
}
public void parse(String xmlFileName) throws FileNotFoundException, IOException,Exception
{
Reader in = new BufferedReader(new InputStreamReader(new FileInputStream(
new File(xmlFileName)), "UTF8"));
try {
parser.setContentHandler(new DbXmlFile());
parser.parse(new InputSource(in));
} catch (SAXException saxe) {
if (saxe instanceof SAXParseException) {
SAXParseException saxpe = (SAXParseException) saxe;
int line = saxpe.getLineNumber();
int col = saxpe.getColumnNumber();
String publicID = saxpe.getPublicId();
String message = "XML parsing exception (" + publicID +
") line " + line + ":" + col;
throw new Exception(message);
}
}
}
public static void main(String[] args) throws Exception
{
DbXmlFile dbXmlFile = new DbXmlFile();
dbXmlFile.parse("d:\\project\\xfk\\db\\date\\20040916134141601.xml");
XML的格式如下
<?xml version="1.0" encoding="GB2312"?>
<ROOT exportDate="2004/09/16 13:42:09.421 CST" beginDate = "2004-09-03"
endDate = "2004-09-21" >
<TSJBLIST/>
<CHECKRECORDLIST>
<CHECKRECORD num="1">
<ID>20040908154750426</ID>
<CHECKTIME>2004-09-07 00:00:00.0</CHECKTIME>
<CHECKER1ID>ddd</CHECKER1ID>
<CHECKER2ID>ddd</CHECKER2ID>
<UNITNAME>南京电视台</UNITNAME>
。。。。。。
,。,,。,,
</ROOT>
}