📄 sax.java
字号:
package com.demo.accp;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.*;
import java.io.*;
public class Sax extends DefaultHandler {
java.util.Stack tags = new java.util.Stack();
String name;
String address;
String tel;
String fax;
String email;
public void endDocument() throws SAXException {
System.out.println("------Parse End--------");
}
public void startDocument() throws SAXException {
System.out.println("------Parse Begin--------");
}
public void startElement(String p0, String p1, String p2, Attributes p3)
throws SAXException {
/*
* startElement(String namespaceURI, String localName, String qName,
* Attributes atts) 限定名称,或 qName。
* 这实际上是名称空间信息(如果有的话)和元素的实际名称的组合。如果有的话,qName 还包括冒号(:) —— 例如,
* revised:response。 名称空间 URI。正如在名称空间中所讨论的,实际的名称空间是某种形式的
* URI,而不是被添加到元素或属性名称的别名。例如,http://www.nicholaschase.com/surveys/revised/
* 而不是简单的 revised:。 本地名称。这是元素的实际名称,比如 question。如果文档没有提供名称空间信息,解析器也许不能确定
* qName 的哪个部分是 localName。 任何属性。元素的属性实际上是作为对象的集合来传递的,
*/
tags.push(p2);
}
public void endElement(String p0, String p1, String tagName)
throws SAXException {
tags.pop();
if (tagName.equals("PERSON"))
printout();
}
public void characters(char[] p0, int p1, int p2) throws SAXException {
/*
* public void characters(char[] ch, int start, int length) throws
* SAXException
*/
String tag = (String) tags.peek();
if (tag.equals("NAME"))
name = new String(p0, p1, p2);
else if (tag.equals("ADDRESS"))
address = new String(p0, p1, p2);
else if (tag.equals("TEL"))
tel = new String(p0, p1, p2);
else if (tag.equals("FAX"))
fax = new String(p0, p1, p2);
else if (tag.equals("EMAIL"))
email = new String(p0, p1, p2);
}
private void printout() {
System.out.print("Name: ");
System.out.println(name);
System.out.print("Address: ");
System.out.println(address);
System.out.print("Tel: ");
System.out.println(tel);
System.out.print("Fax: ");
System.out.println(fax);
System.out.print("Email: ");
System.out.println(email);
System.out.println();
}
static public void main(String[] args) {
String filename = "candidate.xml";// "candidate.xml";
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = null;
try {
saxParser = spf.newSAXParser();
} catch (Exception e) {
System.out.println(e);
System.exit(1);
}
try {
saxParser.parse(new File(filename), new Sax());
} catch (SAXException se) {
System.out.println(se.getMessage());
System.exit(1);
} catch (IOException ioe) {
System.out.println(ioe);
System.exit(1);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -