1. 程式人生 > >DOM解析XML文件例項之學生管理系統

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
    }
}