Read XML By SAX

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();
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值