2.使用jaxp的一个案例(我的JavaEE笔记)

这里我们给出一份xml文档,里面存有一些学生的相关信息,我们需要对这份文档进行相关的解析。

1.首先给出student.xml

(xml/student.xml)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<exam>
    <student examid="222" idcard="111">
        <name>张三</name>
        <location>沈阳</location>
        <grade>89</grade>
    </student>
    
    <student examid="444" idcard="333">
        <name>李四</name>
        <location>大连</location>
        <grade>97</grade>
    </student>


    <student examid="5555" idcard="5555">
        <name>阿猫</name>
        <location>西安</location>
        <grade>86.0</grade>
    </student>
    
</exam>

2.学生实体类

(src/cn.itcast.domain.Student.java)

package cn.itcast.domain;

public class Student {
    private String examId;
    private String idcard;
    private String name;
    private String location;
    private double grade;
    
    
    public String getExamId() {
        return examId;
    }
    public void setExamId(String examId) {
        this.examId = examId;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    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;
    }
        
}

3.工具类

(src/cn.itcast.utils.XmlUtils.java)

package cn.itcast.utils;
import java.io.File;
import javax.management.RuntimeErrorException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import cn.itcast.domain.Student;

public class XmlUtils {
    //将xml文档读到内存中
    public static Document getDocument() throws Exception{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File("xml/student.xml"));
        
        return document;
    }
    
    //将修改过的文档从内存中写到实际的xml文档中
    public static void writeDocument(Document document) throws Exception{
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult(new File("xml/student.xml")));
    }
    
    //添加学生
    public void addStudent(Student student){
        try{
            Document document = XmlUtils.getDocument();
            //得到exam节点
            Node parent = document.getElementsByTagName("exam").item(0);
            //构造一个学生节点
            Element child = document.createElement("student");
            child.setAttribute("examId", student.getExamId());
            child.setAttribute("idcard", student.getIdcard());
            
            Element name = document.createElement("name");
            name.setTextContent(student.getName());
            
            Element location = document.createElement("location");
            location.setTextContent(student.getLocation());
            
            Element grade = document.createElement("grade");//注意:分数是double型的,需要转换成字符串
            grade.setTextContent(student.getGrade() + "");
            
            child.appendChild(name);
            child.appendChild(location);
            child.appendChild(grade);
            parent.appendChild(child);
            
            //将内存中的内容写到xml文档中去
            XmlUtils.writeDocument(document);   
        }catch(Exception e){
            throw new RuntimeException("录入失败!");
        }
    }
    
    //删除学生
    public void deleteStudent(String name) {
        try{
            Document document = XmlUtils.getDocument();
            NodeList list = document.getElementsByTagName("name");
            for(int i = 0; i < list.getLength(); i++){
                Node node = list.item(i);
                if(node.getTextContent().equals(name)){
                    //这里是删除student节点,即name的父节点
                    node.getParentNode().getParentNode().removeChild(node.getParentNode());
                    XmlUtils.writeDocument(document);
                    return;
                }
            }
            throw new RuntimeException("您要删除的学生不存在!!!");
        }catch(Exception e){
            throw new RuntimeException("删除失败!!!");
        }   
    }
    
    //查找学生
    public Student findStudent(String examid){
        try {
            Document document = XmlUtils.getDocument();
            NodeList list = document.getElementsByTagName("student");
            for(int i = 0; i < list.getLength(); i++){
                //因为document中没有取得属性值的方法,所以要转换成Element对象
                
                Element element = (Element) list.item(i);//取得其中一个学生节点
                
                if(element.getAttribute("examid").equals(examid)){
                    Student student = new Student();
                    student.setExamId(examid);
                    student.setIdcard(element.getAttribute("idcard"));
                    student.setName(element.getElementsByTagName("name").item(0).getTextContent());
                    student.setLocation(element.getElementsByTagName("location").item(0).getTextContent());
                    student.setGrade(Double.parseDouble(element.getElementsByTagName("grade").item(0).getTextContent()));
                    
                    return student;
                    
                }
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException("没有您想要查找的学生!!!");
        }   
    }
}

4.测试类

(src/cn.itcast.Demo2.java)

package cn.itcast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.junit.Test;
import cn.itcast.domain.Student;
import cn.itcast.utils.XmlUtils;
public class Demo2 {

    public static void main(String[] args) throws Exception{
        System.out.println("(a)添加                (b)删除              (c)查找");
        System.out.println("请输入您操作类型代号:");
        
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        
        String type = buffer.readLine();
        //添加
        if(type.equalsIgnoreCase("a")){
            try{
                Student stu = new Student();
                System.out.println("请输入学生的姓名:");
                stu.setName(buffer.readLine());
                
                System.out.println("请输入学生的准考证号:");
                stu.setExamId(buffer.readLine());
                
                System.out.println("请输入学生的身份证号:");
                stu.setIdcard(buffer.readLine());
                
                System.out.println("请输入学生的地址:");
                stu.setLocation(buffer.readLine());
                
                System.out.println("请输入学生的分数:");
                stu.setGrade(Double.parseDouble(buffer.readLine()));
                XmlUtils utils = new XmlUtils();
                utils.addStudent(stu);
                System.out.println("录入成功!");
            }catch(Exception e){
                System.out.println(e.getMessage());
            }
        //删除
        }else if(type.equalsIgnoreCase("b")){
            try{
                System.out.println("请输入您要删除学生的名字:");
                String name = buffer.readLine();
                XmlUtils utils = new XmlUtils();
                utils.deleteStudent(name);
                System.out.println("删除成功!");
            }catch(Exception e){
                System.out.println(e.getMessage());
            }
        //查找
        }else if(type.equalsIgnoreCase("c")){
            try{
                System.out.println("请输入您想要查找学生的准考证号:");
                String examid = buffer.readLine();
                Student student = new Student();
                XmlUtils utils = new XmlUtils();
                student = utils.findStudent(examid);
                System.out.println("您要找的学生的信息如下:");
                System.out.println("学生姓名:" + student.getName());
                System.out.println("学生准考证号:" + student.getExamId());
                System.out.println("学生身份证号:" + student.getIdcard());
                System.out.println("学生地址:" + student.getLocation());
                System.out.println("学生分数:" + student.getGrade());
                
            }catch(Exception e){
                System.out.println("查找学生失败!");
            }
        }else{
            System.out.println("没有您想要的操作!!!");
        }
    }
}

注意:这里我们需要注意删除学生的时候。而在异常抛出的时候我们需要注意抛出什么样的异常。而工具类中向上抛出的时候是抛到了测试类中了,我们使用e.getMessage()方法获得抛过来的异常消息。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,730评论 18 399
  • 一. Java基础部分.................................................
    wy_sure阅读 9,311评论 0 11
  • 一:java概述:1,JDK:Java Development Kit,java的开发和运行环境,java的开发工...
    ZaneInTheSun阅读 7,650评论 0 11
  • 一直想拾笔写作,但不知道该怎么开始,直到有人推荐了一些写作的APP,其中首推的就是【简书】,才觉得可以准备开始...
    悦悦_961b阅读 2,607评论 0 0
  • 建立一个标准,不仅是为重复的行为设置流程方案,更是在这个领域里面成为分析总结达人的必经之路。 你的工作、学习和生活...
    芭菲小鹿阅读 1,571评论 0 1

友情链接更多精彩内容