package com.test.xml;
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLBySAX extends DefaultHandler {
private String tagValue;
long starttime;
long endtime;
public static void main(String[] args) {
String filename = "E:\\Computer.xml";
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser saxParser = spf.newSAXParser();
saxParser.parse(new File(filename), new ReadXMLBySAX());
} catch (Exception e) {
e.printStackTrace();
}
}
// 开始解析XML文件
public void startDocument() throws SAXException {
// 可以在此初始化变量等操作
System.out.println("~~~~解析文档开始~~~");
// starttime=System.currentTimeMillis();
starttime = System.nanoTime();
}
// 结束解析XML文件
public void endDocument() throws SAXException {
// endtime=System.currentTimeMillis();
endtime = System.nanoTime();
System.out.println("~~~~解析文档结束~~~");
// System.out.println("共用"+(endtime-starttime)+"毫秒");
System.out.println("共用" + (endtime - starttime) + "纳秒");
}
/**
* 在解释到一个开始元素时会调用此方法.但是当元素有重复时可以自己写算法来区分
*
*/
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
System.out.println("startElement处标签名:" + qName);
if (attributes != null && attributes.getLength() != 0) {
System.out.print("--" + "该标签有属性值:");
for (int i = 0; i < attributes.getLength(); i++) {
System.out.print(attributes.getQName(i) + "=");
System.out.print(attributes.getValue(i) + " ");
}
System.out.println();
}
}
/**
* 在遇到结束标签时调用此方法
*/
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.print("endElement处的值是:");
System.out.println(tagValue);
}
/**
* 所有的XML文件中的字符会放到ch[]中
*/
public void characters(char ch[], int start, int length)
throws SAXException {
tagValue = new String(ch, start, length).trim();
}
}
Read XML By SAX
最新推荐文章于 2023-08-12 12:16:37 发布