DOM解析XML文档实例之学生管理系统

/**
*@ author StormMaybin
*@ date 2016-10-06
*/

生命不息,奋斗不止!


需求分析:

用XML文档来保存学生信息,

通过对XML文档的增删改,来实现管理学生信息的功能。

主体结构

这里写图片描述

学生类
package com.stormma.domain;

public class Student
{
    private String idCard;
    private String examId;
    private String name;
    private String location;
    private double grade;
    public String getIdCard()
    {
        return idCard;
    }
    public void setIdCard(String idCard)
    {
        this.idCard = idCard;
    }
    public String getExamId()
    {
        return examId;
    }
    public void setExamId(String examId)
    {
        this.examId = examId;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getLocation()
    {
        return location;
    }
    public void setLocation(String location)
    {
        this.location = location;
    }
    public double getGrade()
    {
        return grade;
    }
    public void setGrade(double grade)
    {
        this.grade = grade;
    }
    @Override
    public String toString()
    {
        // TODO Auto-generated method stub
        return "姓名: "+this.name
                +"\r\n"+"身份证号:"+this.idCard
                +"\r\n"+"准考证号:"+this.examId
                +"\r\n"+"出生地:"+this.location
                +"\r\n"+"成绩:"+this.grade;
    }
}
XML工具类
package com.stormma.utils;

import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

/**
 * @author StormMaybin writeToXML()方法 getDocument()方法
 */
public class XMLUtils
{
    private static final String fileName = "src/exam.xml";

    public static Document getDocument() throws Exception
    {
        // 获得工厂实例
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 获得解析器
        DocumentBuilder builder = factory.newDocumentBuilder();
        // 解析文档
        return builder.parse(fileName);
    }

    public static void writeToXML(Document document) throws Exception
    {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.transform(new DOMSource(document), new StreamResult(
                new FileOutputStream(fileName)));
    }
}
操作XML文档的StudentDao类
package com.stormma.dao;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.stormma.domain.Student;
import com.stormma.exception.StudentNotExistException;
import com.stormma.utils.XMLUtils;
/**
 * 用来和数据库(XML文件)交互
 * @author StormMaybin
 *  操作:添加学生、查询学生、删除学生
 */
public class StudentDao
{
    public void add (Student s)
    {
        try
        {
            //得到对应XML文档对象
            Document document = XMLUtils.getDocument();

            //创建学生标签
            Element student_tag = document.createElement("student");
            //设置student标签的属性
            student_tag.setAttribute("idCard", s.getIdCard());
            student_tag.setAttribute("examId", s.getExamId());

            //创建student标签的子标签
            Element name = document.createElement("name");
            Element location = document.createElement("location");
            Element grade = document.createElement("grade");

            //设置标签内容
            name.setTextContent(s.getName());
            location.setTextContent(s.getLocation());
            grade.setTextContent(s.getGrade()+"");

            //建立标签关系
            student_tag.appendChild(name);
            student_tag.appendChild(location);
            student_tag.appendChild(grade);

            //得到student父节点
            Element exam = (Element) document.getElementsByTagName("exam").item(0);
            exam.appendChild(student_tag);

            //更新文档内容
            XMLUtils.writeToXML(document);
        } 
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            //异常转型
            throw new RuntimeException(e);
        }
    }
    public Student find (String examId)
    {
        try
        {
            //得到对应XML文档对象
            Document document = XMLUtils.getDocument();

            //得到学生标签集合
            NodeList sList = document.getElementsByTagName("student");
            for (int i = 0; i < sList.getLength(); i++)
            {
                Element student = (Element) sList.item(i);
                if (student.getAttribute("examId").equals(examId))
                {
                    //封装学生对象,返回
                    Student s = new Student();
                    s.setExamId(examId);
                    s.setIdCard(student.getAttribute("idCard"));
                    s.setName(student.getElementsByTagName("name").item(0).getTextContent());
                    s.setLocation(student.getElementsByTagName("location").item(0).getTextContent());
                    s.setGrade(Double.parseDouble(student.getElementsByTagName("grade").item(0).getTextContent()));

                    //返回学生对象
                    return s;
                }
            }
            return null;
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
//          e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public void delete (String name) throws StudentNotExistException
    {
        try
        {
            //得到对应XML文档对象
            Document document = XMLUtils.getDocument();

            //得到学生姓名集合
            NodeList nList = document.getElementsByTagName("name");
            for (int i = 0; i < nList.getLength(); i++)
            {
                if (nList.item(i).getTextContent().equals(name))
                {
                    nList.item(i).getParentNode().getParentNode().removeChild(nList.item(i).getParentNode());
                    //更新文档
                    XMLUtils.writeToXML(document);
                    return;
                }
            }
            throw new StudentNotExistException(name+"不存在");
        }
        catch (StudentNotExistException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            throw new RuntimeException(e);
        }
    }
}
程序入口
package com.stormma.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

import com.stormma.dao.StudentDao;
import com.stormma.domain.Student;
import com.stormma.exception.StudentNotExistException;

public class Main
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        meun();
        // BufferedReader br = new BufferedReader(new
        // InputStreamReader(System.in));
        Scanner br = new Scanner(System.in);
        while (br.hasNext())
        {
            try
            {
                String type = br.next();
                if (type.equals("a"))
                {
                    System.out.println("请输入要添加学生的姓名 ");
                    String name = br.next();

                    System.out.println("请输入要添加学生的准考证号 ");
                    String examId = br.next();

                    System.out.println("请输入要添加学生的身份证号 ");
                    String idCard = br.next();

                    System.out.println("请输入要添加学生的出生地 ");
                    String location = br.next();

                    System.out.println("请输入要添加学生的分数 ");
                    String grade = br.next();

                    Student s = new Student();
                    s.setExamId(examId);
                    s.setName(name);
                    s.setGrade(Double.parseDouble(grade));
                    s.setLocation(location);
                    s.setIdCard(idCard);

                    StudentDao sd = new StudentDao();
                    sd.add(s);

                    System.out.println("添加成功");
                } else if (type.equals("b"))
                {
                    System.out.println("请输入你要删除的学生的姓名");
                    String name = br.next();

                    try
                    {
                        StudentDao sd = new StudentDao();
                        sd.delete(name);
                        System.out.println("删除成功");
                    } catch (StudentNotExistException e)
                    {
                        System.out.println("您要删除的学生不存在");
                    }
                } else if (type.equals("c"))
                {
                    System.out.println("请输入你要查询的学生的准考证号");
                    String examId = br.next();
                    StudentDao sd = new StudentDao();

                    if (sd.find(examId) != null)
                    {
                        System.out.println(sd.find(examId));
                    } else
                    {
                        System.out.println("您要查找的学生不存在");
                    }
                } else
                {
                    System.out.println("请键入正确的操作");
                }
            } catch (Exception e)
            {
                e.printStackTrace();
                System.out.println("系统正忙······");
            }
        }
    }

    public static void meun()
    {
        System.out.println("********欢迎进入学生管理系统********");
        System.out.println("\t添加用户:a");
        System.out.println("\t删除用户:b");
        System.out.println("\t查找用户:c");
        System.out.println("*********************************");
        System.out.print("请选择:");
    }
}
自定义异常
package com.stormma.exception;

public class StudentNotExistException extends Exception
{

    public StudentNotExistException()
    {
        // TODO Auto-generated constructor stub
    }

    public StudentNotExistException(String message)
    {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public StudentNotExistException(Throwable cause)
    {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public StudentNotExistException(String message, Throwable cause)
    {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public StudentNotExistException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace)
    {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }
}

源码连接:XML案例之学生管理系统

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值