SAXParser解析xml文件

对于xml的解析,这里学习并演示使用SAXParser进行解析的样例。

使用此种方法无法解析"gb2312"编码的xml文件,因此,此处xml文件编码设置为"UTF-8"

1. person.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<person>
<name>王飞</name>
<college>理工大学</college>
<telephone>2663457</telephone>
<title>教授</title>
</person>

2.java相关代码

import java.io.File;
import java.io.FileReader;
import java.util.Hashtable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TestParse {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
try {
File file = new File("person.xml");
FileReader reader = new FileReader(file);
// 创建解析工厂实例
SAXParserFactory spf = SAXParserFactory.newInstance();
// 创建解析器
SAXParser sp = spf.newSAXParser();
// 创建处理类实例
SAXHandler handler = new SAXHandler();

// 解析
sp.parse(new InputSource(reader), handler);

// 此类实现一个哈希表,该哈希表将键映射到相应的值。任何非 null 对象都可以用作键或值。
Hashtable hashTable = handler.getTable();
// 输出数据
System.out.println("教师信息表");
System.out.println("姓名:"
+ (String) hashTable.get(new String("name")));
System.out.println("学院:"
+ (String) hashTable.get(new String("college")));
System.out.println("电话:"
+ (String) hashTable.get(new String("telephone")));
System.out.println("职称:"
+ (String) hashTable.get(new String("title")));
} catch (Exception e) {
System.out.println(e.getMessage());
}

}

}

// 自定义处理类
class SAXHandler extends DefaultHandler {
@SuppressWarnings("unchecked")
private Hashtable table = new Hashtable();
private String currentElement = null;
private String currentValue = null;

@SuppressWarnings("unchecked")
public Hashtable getTable() {
return table;
}

// 覆盖startElement方法,取出节点标签
public void startElement(String uri, String localName, String qName,
Attributes attributes) {
currentElement = qName;
}

// 覆盖characters方法,取出节点值
public void characters(char[] ch, int start, int length)
throws SAXException {
currentValue = new String(ch, start, length);
}

// 覆盖endElement方法,放入Hashtable
@SuppressWarnings("unchecked")
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (currentElement.equals(qName))
table.put(currentElement, currentValue);
}

}

3.运行结果

原文地址:https://www.cnblogs.com/binfoo/p/4864596.html