javaweb-day01-7(XML 解析-案例)

2024-09-07 16:08
文章标签 java xml web 解析 案例 day01

本文主要是介绍javaweb-day01-7(XML 解析-案例),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、以如下格式的exam.xml文件为例

exam.xml

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



2、编程实现如下功能

 

3、实现学生信息的添加

 

4、实现学生信息的查询

 

5、实现学生的删除功能

 

 

添加数据:


查询数据:


 

开发顺序:先写javabean,再写Dao用到的工具类、Dao ,最后写界面层Main。

不同模块的程序,要放在不同的包里:

  •   实体javabean:放在domain包。
  •   Dao:放在dao包。dao操作xml文档必定会有重复代码:得到document、更新xml文档。将他们抽取到工具类XmlUtils里。
  •   工具类XmlUtils:放在utils工具包中。
  •   界面Main:放在main包。

 

 

Student.java

package cn.mengmei.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;}}



XMLUtils.java

package cn.mengmei.utils;import java.io.IOException;import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;
import org.xml.sax.SAXException;public class XMLUtils {public static Document document() throws SAXException, IOException, ParserConfigurationException  {Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("src/exam.xml");return document;}public static void updateXML(Document document) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError  {TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult("src/exam.xml"));}
}


 

StudentDao.java

package cn.mengmei.dao;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;import cn.mengmei.domain.Student;
import cn.mengmei.utils.XMLUtils;public class StudentDao {public void add(Student student) {try {Document document = XMLUtils.document();Element stuNode = document.createElement("student");stuNode.setAttribute("idcard", student.getIdcard());stuNode.setAttribute("examid", student.getExamid());Element nameNode = document.createElement("name");nameNode.setTextContent(student.getName());Element locNode = document.createElement("location");locNode.setTextContent(student.getLocation());Element graNode = document.createElement("grade");graNode.setTextContent(student.getGrade()+"");stuNode.appendChild(nameNode);stuNode.appendChild(locNode);stuNode.appendChild(graNode);document.getDocumentElement().appendChild(stuNode);XMLUtils.updateXML(document);} catch (Exception e) {throw new RuntimeException(e);}}public void delete(String name){try {Document document = XMLUtils.document();NodeList nameList = document.getElementsByTagName("name");for(int i=0;i<nameList.getLength();i++){Node nameNode = nameList.item(i);if(nameNode.getTextContent().equals(name)){Node stuNode = nameNode.getParentNode();stuNode.getParentNode().removeChild(stuNode);XMLUtils.updateXML(document);return;}}throw new RuntimeException("-------对不起,你要删除的学生信息不存在!------");  //异常也是一种返回值。} catch (Exception e) {throw new RuntimeException(e);}}public Student find(String examid){Document document = null;try {document = XMLUtils.document();NodeList stuList = document.getElementsByTagName("student");Student student = null;for(int i=0;i<stuList.getLength();i++){Element stuNode = (Element)stuList.item(i);if(Integer.parseInt(stuNode.getAttribute("examid")) == Integer.parseInt(examid)){student = new Student();student.setName(stuNode.getElementsByTagName("name").item(0).getTextContent());student.setIdcard(stuNode.getAttribute("idcard"));student.setExamid(stuNode.getAttribute("examid"));student.setLocation(stuNode.getElementsByTagName("location").item(0).getTextContent());student.setGrade(Double.parseDouble(stuNode.getElementsByTagName("grade").item(0).getTextContent()));}}return student;} catch (Exception e) {throw new RuntimeException(e);}}}



Main.java

package cn.mengmei.main;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;import cn.mengmei.dao.StudentDao;
import cn.mengmei.domain.Student;public class Main {public static void main(String[] args) {System.out.println("添加用户:(a)    删除用户:(b)    查询成绩:(c)");System.out.print("请输入操作类型:");BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String item = null;try {item = reader.readLine();} catch (IOException e1) {System.out.println("--------对不起,读取类型失败!--------");}String name = null;String idcard = null;String examid = null;String location = null;String grade = null;Student student = null;StudentDao dao = null;switch (item) {case "a":try {System.out.print("请输入学生姓名:");name = reader.readLine();System.out.print("请输入学生身份证号:");idcard = reader.readLine();System.out.print("请输入学生准考证号:");examid = reader.readLine();System.out.print("请输入学生所在地:");location = reader.readLine();System.out.print("请输入学生成绩:");grade = reader.readLine(); student = new Student();student.setName(name);student.setIdcard(idcard);student.setExamid(examid);student.setLocation(location);student.setGrade(Double.parseDouble(grade));dao = new StudentDao();dao.add(student);System.out.println("-----------添加数据成功-----------");} catch (Exception e) {System.out.println("-----------对不起,添加数据失败!-----------");}break;case "b":try {System.out.print("请输入要删除的学生姓名:");name = reader.readLine();dao = new StudentDao();dao.delete(name);System.out.println("------对已成功删除学生信息------");} catch (Exception e) {System.out.println(e.getMessage());}break;case "c":try {System.out.print("请输入要查询的学生准考证号:");examid = reader.readLine();dao = new StudentDao();student = dao.find(examid);if(student!=null){System.out.println("姓名:"+student.getName());System.out.println("身份证号:"+student.getIdcard());System.out.println("准考证号:"+student.getExamid());System.out.println("所在地:"+student.getLocation());System.out.println("成绩:"+student.getGrade());}else{System.out.println("--------对不起,没有查询到此学生!-------");}} catch (Exception e) {System.out.println("------对不起,查询失败!------");}break;default:System.out.println("-------非法类型-------");break;}}}



 

 

这篇关于javaweb-day01-7(XML 解析-案例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1145525

相关文章

PyTorch核心方法之state_dict()、parameters()参数打印与应用案例

《PyTorch核心方法之state_dict()、parameters()参数打印与应用案例》PyTorch是一个流行的开源深度学习框架,提供了灵活且高效的方式来训练和部署神经网络,这篇文章主要介绍... 目录前言模型案例A. state_dict()方法验证B. parameters()C. 模型结构冻

R语言中的正则表达式深度解析

《R语言中的正则表达式深度解析》正则表达式即使用一个字符串来描述、匹配一系列某个语法规则的字符串,通过特定的字母、数字及特殊符号的灵活组合即可完成对任意字符串的匹配,:本文主要介绍R语言中正则表达... 目录前言一、正则表达式的基本概念二、正则表达式的特殊符号三、R语言中正则表达式的应用实例实例一:查找匹配

springboot控制bean的创建顺序

《springboot控制bean的创建顺序》本文主要介绍了spring-boot控制bean的创建顺序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录1、order注解(不一定有效)2、dependsOn注解(有效)3、提前将bean注册为Bea

Java中的ConcurrentBitSet使用小结

《Java中的ConcurrentBitSet使用小结》本文主要介绍了Java中的ConcurrentBitSet使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、核心澄清:Java标准库无内置ConcurrentBitSet二、推荐方案:Eclipse

java中的Supplier接口解析

《java中的Supplier接口解析》Java8引入的Supplier接口是一个无参数函数式接口,通过get()方法延迟计算结果,它适用于按需生成场景,下面就来介绍一下如何使用,感兴趣的可以了解一下... 目录1. 接口定义与核心方法2. 典型使用场景场景1:延迟初始化(Lazy Initializati

Java中ScopeValue的使用小结

《Java中ScopeValue的使用小结》Java21引入的ScopedValue是一种作用域内共享不可变数据的预览API,本文就来详细介绍一下Java中ScopeValue的使用小结,感兴趣的可以... 目录一、Java ScopedValue(作用域值)详解1. 定义与背景2. 核心特性3. 使用方法

spring中Interceptor的使用小结

《spring中Interceptor的使用小结》SpringInterceptor是SpringMVC提供的一种机制,用于在请求处理的不同阶段插入自定义逻辑,通过实现HandlerIntercept... 目录一、Interceptor 的核心概念二、Interceptor 的创建与配置三、拦截器的执行顺

Java中Map的五种遍历方式实现与对比

《Java中Map的五种遍历方式实现与对比》其实Map遍历藏着多种玩法,有的优雅简洁,有的性能拉满,今天咱们盘一盘这些进阶偏基础的遍历方式,告别重复又臃肿的代码,感兴趣的小伙伴可以了解下... 目录一、先搞懂:Map遍历的核心目标二、几种遍历方式的对比1. 传统EntrySet遍历(最通用)2. Lambd

Spring Boot 中 RestTemplate 的核心用法指南

《SpringBoot中RestTemplate的核心用法指南》本文详细介绍了RestTemplate的使用,包括基础用法、进阶配置技巧、实战案例以及最佳实践建议,通过一个腾讯地图路线规划的案... 目录一、环境准备二、基础用法全解析1. GET 请求的三种姿势2. POST 请求深度实践三、进阶配置技巧1

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi