-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathSAXParserDemo.java
More file actions
51 lines (51 loc) · 1.27 KB
/
SAXParserDemo.java
File metadata and controls
51 lines (51 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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;
/**
* 使用java的SAX方法来操作xml文档
* */
public class SAXParserDemo
{
private static File file = new File("D://Demo.xml");
public static void main(String[] args) throws Exception
{
test();
}
public static void test()throws Exception
{
//1创建解析工厂类
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();//
//2,创建自定义类
MyDefaultHandler mh = new MyDefaultHandler();
//2解析xml文件
sp.parse(file, mh);
}
}
//自定义DefaultHandler类
class MyDefaultHandler extends DefaultHandler
{
/**
* 当解析到一个开始标签的时候执行
* */
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
{
System.out.print("<"+qName+">");
}
/**
* 当执行到文本内容的时候,包括空格和换行
* */
public void endElement(String uri, String localName, String qName)throws SAXException
{
System.out.print("</"+qName+">");
}
/**
* 当执行到结束标签的时候执行这个方法
* */
public void characters(char[] ch, int start, int length)throws SAXException
{
System.out.print(new String(ch,start,length));
}
}