前端之家收集整理的这篇文章主要介绍了
学生数据插入XML,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
需要导入dom4j包
package aa;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import vo.Student;
public class Lianxi {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
Set set=new TreeSet();
while(true)
{
System.out.println("1.学员信息录入");
System.out.println("2.查询信息");
int oper=sc.nextInt();
if(oper==1){
//获取学员信息
System.out.println("请输入学员姓名: ");
String name=sc.next();
System.out.println("请输入学员年龄: ");
int age=sc.nextInt();
System.out.println("请输入学员班级: ");
int banji=sc.nextInt();
Student stu=new Student(name,age,banji);
set.add(stu);}
if(oper==2){
System.out.println("等会实现。。");
}
System.out.println("按1继续,其他键退出...");
oper=sc.nextInt();
if(oper!=1)
{
break;
}
}
Document xml = DocumentHelper.createDocument();
//2.在xml文档创建根目录
Element root =xml.addElement("学员信息表");
//3.创建相应的子目录
Iterator it=set.iterator();
while(it.hasNext()){
Student value=(Student)it.next();
String banji="班级"+value.getBanji();
Element currentElement=root.element(banji);
if(currentElement!=null){
Element stuE= currentElement.addElement("学生");
stuE.addElement("姓名").setText(value.getName());
stuE.addElement("年龄").setText(value.getAge()+"");
}else{
currentElement=root.addElement(banji);
Element stuE= currentElement.addElement("学生");
stuE.addElement("姓名").setText(value.getName());
stuE.addElement("年龄").setText(value.getAge()+"");
}
//4.指定当前xml文档使用的字符集
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
//5.指明内存中的xml文档将要在硬盘上的位置
XMLWriter writer = new XMLWriter(new FileOutputStream("d://学员.xml"),format);
//6.向硬盘传输内容
writer.write(xml);
//7.close
writer.close();
}
}
}
package vo;
public class Student implements Comparable {
private String name;
private int banji;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBanji() {
return banji;
}
public void setBanji(int banji) {
this.banji = banji;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name,int age,int banji2){
super();
this.name=name;
this.banji=banji2;
this.age=age;
}
@Override
public int compareTo(Object o) {
Student s2=(Student)o;
if(s2.getBanji()<this.banji){
return 1;
}else if(s2.getBanji()>this.banji)
{return -1;}
else if(s2.getBanji()==this.banji){
if(s2.age>this.age){return -1;}
else if(s2.age<this.age){return 1;}
else {return 0;}
}
return 1;
}
}