XML实现简单学生管理系统

使用xml当作数据库,存储学生信息

// 增加
	public static void addStu(StudentDemo student) throws DocumentException, IOException {
		/*
		 * 1、创建解析器
		 * 2、获得document
		 * 3、获得根节点
		 * 4、在根节点上添加stu标签
		 * 5、在stu标签上依次添加id、name、age
		 * 6、在id、name、age上面依次添加值
		 * 7、回写xml
		 */
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read("src/student.xml");
		Element root = document.getRootElement();
		
		Element stu = root.addElement("stu");
		Element id = stu.addElement("id");
		Element name = stu.addElement("name");
		Element age = stu.addElement("age");
		
		id.setText(student.getId());
		name.setText(student.getName());
		age.setText(student.getAge());
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/student.xml"), format);
		xmlWriter.write(document);
		xmlWriter.close();
	}
//删除
	//根据student id删除
	
	public static void 	delStu(String id) throws DocumentException, IOException {
		/*
		 * 1、创建解析器
		 * 2、获得document
		 * 3、获得id  通过xpath
		 * 4、遍历list集合
		 * 5、判断list内id和传递的id是否相同
		 * 6、如果相同,把id所造stu删除
		 * 7、回写xml
		 */
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read("src/student.xml");
		
		List<Node> list = document.selectNodes("//id");
		
		for (Node node : list) {
			String idv = node.getText();
			if(idv.equals(id)) {
				Element stu = node.getParent();
				Element student = stu.getParent();
				student.remove(stu);
			}
		}
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/student.xml"),format);
		xmlWriter.write(document);
		xmlWriter.close();
	}
//查询 更具id查询
	
	public static StudentDemo selectStu(String id) throws DocumentException {
		/*
		 * 1、创建解析器
		 * 2、获得document
		 * 3、获得所有id通过xpath
		 * 4、遍历list集合
		 * 5、判断list内id和传递的id是否相同
		 * 6、相同则找到父节点stu
		 * 7、得到stu的id,name,age值
		 */
		StudentDemo student = new StudentDemo();
		
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read("src/student.xml");
		
		List<Node> list = document.selectNodes("//id");
		
		for (Node node : list) {
			String idv = node.getText();
			
			if(idv.equals(id)) {
				Element stu = node.getParent();
				String namev = stu.element("name").getText();
				String agev = stu.element("age").getText();
				student.setId(id);
				student.setName(namev);
				student.setAge(agev);
			}
			
		}
		
		return student;
	}

发表评论

电子邮件地址不会被公开。 必填项已用*标注