java.lang.ClassCastException: org.apache.xerces.dom.DocumentImpl cannot be cast to org.apache.crimson.tree.XmlDocument 解决方法!
package Student;
/**
* @author 作者 E-mail: feixianyexin@163.com
* @version 创建时间:2007-7-22 上午10:43:35
* @ description 类说明
*/
import java.io.*; //Java基础包,包含各种IO操作
import java.util.*; //Java基础包,包含各种标准数据结构操作
import javax.xml.parsers.*; //XML解析器接口
import org.w3c.dom.*; //XML的DOM实现
import org.apache.crimson.tree.XmlDocument;//写XML文件要用到
public class XMLTest {
Vector student_Vector;
XMLTest() {
}
private void readXMLFile(String inFile) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.err.println(pce); //出异常时输出异常信息,然后退出,下同
System.exit(1);
}
Document doc = null;
try {
doc = db.parse(inFile);
} catch (DOMException dom) {
System.err.println(dom.getMessage());
System.exit(1);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
//下面是解析XML的全过程,比较简单,先取根元素 "学生花名册 "
Element root = doc.getDocumentElement();
//取 "学生 "元素列表
NodeList students = root.getElementsByTagName( "学生 ");
for (int i = 0; i < students.getLength(); i++) {
//依次取每个 "学生 "元素
Element student = (Element) students.item(i);
//创建一个学生的Bean实例
StudentBean studentBean = new StudentBean();
//取学生的性别属性
studentBean.setSex(student.getAttribute( "性别 "));
//取 "姓名 "元素,下面类同
NodeList names = student.getElementsByTagName( "姓名 ");
if (names.getLength() == 1) {
Element e = (Element) names.item(0);
Text t = (Text) e.getFirstChild();
studentBean.setName(t.getNodeValue());
}
NodeList ages = student.getElementsByTagName( "年龄 ");
if (ages.getLength() == 1) {
Element e = (Element) ages.item(0);
Text t = (Text) e.getFirstChild();
studentBean.setAge(Integer.parseInt(t.getNodeValue()));
}
NodeList phones = student.getElementsByTagName( "电话 ");
if (phones.getLength() == 1) {
Element e = (Element) phones.item(0);
Text t = (Text) e.getFirstChild();
studentBean.setPhone(t.getNodeValue());
}
student_Vector.add(studentBean);
}
}
private void writeXMLFile(String outFile) throws Exception {
//为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.err.println(pce);
System.exit(1);
}
Document doc = null;
doc = db.newDocument();
//下面是建立XML文档内容的过程,先建立根元素 "学生花名册 "
Element root = doc.createElement( "学生花名册 ");
//根元素添加上文档
doc.appendChild(root);
//取学生信息的Bean列表
for (int i = 0; i < student_Vector.size(); i++) {
//依次取每个学生的信息
StudentBean studentBean = (StudentBean) student_Vector.get(i);
//建立 "学生 "元素,添加到根元素
Element student = doc.createElement( "学生 ");
student.setAttribute( "性别 ", studentBean.getSex());