📄 sax_test.java
字号:
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
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 SAX_test extends DefaultHandler {
static private Writer out;//生成一个输出对象
/**
* 打印函数。功能比较简单,仅仅负责将传入的字符串输出至控制台
*/
private void print(String s) throws SAXException {
try {
out.write(s);
out.flush();
} catch (IOException e) {
e.printStackTrace();
throw new SAXException("I/O error", e);
}
}
/**
* 打印一个新行。很简单的功能。
*/
private void newLine() throws SAXException {
String lineEnd = System.getProperty("line.separator");
try {
out.write(lineEnd);
} catch (IOException e) {
throw new SAXException("I/O error", e);
}
}
/**
* 文档开始。打印xml的声明语句,其中\"为转义字符,目的是输出"
*/
public void startDocument() throws SAXException {
print("<?xml version=\"1.0\" encoding=\"GB2312\"?>");
newLine();
}
/**
* 文档结否。打印一个新行
*/
public void endDocument() throws SAXException {
newLine();
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 开始读取元素。
*/
public void startElement(String uri, String localName, String qName,
Attributes attrs) throws SAXException {
print("<" + qName); //打印元素名
if (attrs != null) { //打印元素的所有属性名及值
for (int i = 0; i < attrs.getLength(); i++) {
print(" ");
print(attrs.getQName(i) + "=\"" + attrs.getValue(i) + "\"");
}
}
print(">");
}
/**
* 读取元素结束。打印元素元素的结束标识
*/
public void endElement(String uri, String localName, String qName)
throws SAXException {
print("</" + qName + ">");
}
/**
* 读取元素中的数据。这是开发人员最为关心的地方。在此将元素中的字符串数组
* 构造成一个字符串然后打印出来
*/
public void characters(char buf[], int offset, int len) throws SAXException {
String s = new String(buf, offset, len);
print(s);
}
/**
* 在主函数中需要输入载入的xml文档路径
*/
public static void main(String argv[]) {
if (argv.length != 1) {
System.err.println("Usage: cmd filename");
System.exit(1);
}
try {
// 设定输出流
out = new OutputStreamWriter(System.out, "GB2312");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new File(argv[0]), new SAX_test());//通过本身作为解析器解析XML文档
} catch (Throwable t) {
t.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -