📄 saxreader.java
字号:
import java.io.*;
import java.net.*;
import java.util.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import org.xml.sax.helpers.*;
import org.xml.sax.helpers.DefaultHandler;
public class SAXReader extends DefaultHandler {
// 使用栈来存储数据
java.util.Stack tags=new java.util.Stack();
// 定义和XML文件中标记对应的变量
String text=null;
String url=null;
String author=null;
String description=null;
String day=null;
String year=null;
String month=null;
// 当遇到文档结束标记时自动触发endDocument()方法
public void endDocument() throws SAXException {
System.out.println("------Parse End--------");
}
// 当遇到文档开始标记时自动触发startDocument()方法
public void startDocument() throws SAXException {
System.out.println("------Parse Begin--------");
}
// 当遇到标记开始记时会自动触发startElement()方法
public void startElement(String p0, String p1, String p2, Attributes p3) throws SAXException {
// 参数p0对应的是名空间的URI,如没有则为空串
// 参数p1对应的是名空间的局部名,如没有则为空串
// 参数p2对应的是标记名
// 参数p3对应的是属性名
// System.out.println(p0 + ":" + p1 + ":" +p2);
tags.push(p2);
}
public void endElement(String p0, String p1, String p2) throws SAXException {
tags.pop();
// 当一link节点的信息收集齐,即将其格式化输出
if (p2.equals("link")) printout();
}
// characters方法的第一个参数p0: 是包含字符串数据的字符数组
// characters方法的第二个参数p1: 是起始位置
// characters方法的第三个参数p2: 是结束位置
// 注意:标记和标记之间的空格也会被计算
public void characters(char[] p0, int p1, int p2) throws SAXException {
//从栈中得到当前节点的信息
String tag=(String) tags.peek();
if (tag.equals("text")) text=new String(p0,p1,p2);
else if (tag.equals("url")) url=new String(p0,p1,p2);
else if (tag.equals("author")) author=new String(p0,p1,p2);
else if (tag.equals("day")) day=new String(p0,p1,p2);
else if (tag.equals("month")) month=new String(p0,p1,p2);
else if (tag.equals("year")) year=new String(p0,p1,p2);
else if (tag.equals("description")) description=new String(p0,p1,p2);
}
private void printout(){
System.out.print("Content: ");
System.out.println(text);
System.out.print("URL: ");
System.out.println(url);
System.out.print("Author: ");
System.out.println(author);
System.out.print("Date: ");
System.out.println(day+"-"+month+"-"+year);
System.out.print("Description: ");
System.out.println(description);
System.out.println();
}
static public void main(String[] args) {
String filename = null;
boolean validation = false;
filename="mylinks.xml";
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser=null;
try {
saxParser = spf.newSAXParser();
} catch (Exception ex) {
System.err.println(ex);
System.exit(1);
}
try {
saxParser.parse(new File(filename),new SAXReader());
} catch (SAXException se) {
System.err.println(se.getMessage());
System.exit(1);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -