欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

文件io之(用jdom解析xml)

程序员文章站 2022-05-28 12:17:28
...

文件io之(用jdom解析xml)

下面是将xml解析到txt

xml中内容如下:

<?xml version="1.0" encoding="utf-8"?>
<students>
     <student>
          <学号>201833</学号>
          <学生姓名>王二</学生姓名>
          <课程 课程名="操作系统">70</课程>
     </student>
     <student>
          <学号>201834</学号>
          <学生姓名>张三</学生姓名>
          <课程 课程名="操作系统">90</课程>
          <课程 课程名="嵌入式系统">20</课程>
     </student>
</students>

txt中内容如下:

201833,王二,操作系统,70
201834,张三,操作系统,90
201834,张三,嵌入式系统,20

package lastdaytest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.*;
import org.jdom2.input.SAXBuilder;

public class textToxml {
	
	public static ArrayList<String> readFile(String filename){
		ArrayList<String> list = new ArrayList<String>();
		try {
			File file = new File(filename);
			SAXBuilder parser = new SAXBuilder();
			Document doc = parser.build(file);
			Element students = doc.getRootElement();
			List<Element> student =students.getChildren("student");
			for(int i=0;i<student.size();i++) {
				String stuNo = student.get(i).getChildText("学号");
				String stuName = student.get(i).getChildText("学生姓名");
				List<Element> courses = student.get(i).getChildren("课程");
				for(int j=0;j<courses.size();j++) {
					String coursename = courses.get(j).getAttributscore;
					list.add(s);
				}
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return list;
	}
	
	public static void WriteFile(ArrayList<String> list,String filename) {
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
			for(String s : list) {
				bw.write(s);
				bw.newLine();
				bw.flush();
			}
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	

	public static void main(String[] args) {
          ArrayList<String> list = readFile("H:\\output.xml");
          WriteFile(list,"H:\\b.txt");
	}

}

将txt中的内容用以xml的形式解析出来
student类

package io;

import java.util.ArrayList;

public class Student {
       private String studentId;
       private String studentName;
       private ArrayList<Course> Courses;
       
       
    public Student(String studentId,String studentName,ArrayList<Course> Courses) {
    	this.studentId=studentId;
    	this.studentName = studentName;
    	this.Courses =Courses;
    }
	public String getStudentId() {
		return studentId;
	}
	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public ArrayList<Course> getCourses() {
		return Courses;
	}
	public void setCourses(ArrayList<Course> courses) {
		Courses = courses;
	}
}

course类

package io;

public class Course {
private String courseName;
private int score;

public Course(String courseName,int score) {
	this.courseName = courseName;
	this.score = score;
}
public String getCourseName() {
	return courseName;
}
public void setCourseName(String courseName) {
	this.courseName = courseName;
}
public int getScore() {
	return score;
}
public void setScore(int score) {
	this.score = score;
}

}

解析txt到mxl

package io;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.io.*;
import org.jdom2.*;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class txtTOxml {

	public  static ArrayList<String> readFile(String filename){
		ArrayList<String> list = new ArrayList<>();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename))));
			String inLine=null;
			while((inLine=br.readLine())!=null) {
				list.add(inLine);
			}
			br.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	
	public static void WriteFile(Map<String,Student> m,String filename) {
		Document doc = new Document();
		Element students = new Element("Students");
		doc.addContent(students);
		Element student =null;
		
		for(String s:m.keySet()) {
			if(m.containsKey(s)) {
	            student = new Element("student");
				Element sno = new Element("学号");
				sno.setText(m.get(s).getStudentId().toString());
				student.addContent(sno);
				Element sname = new Element("学生姓名");
				sname.setText(m.get(s).getStudentName().toString());
				student.addContent(sname);
				for(Course c:m.get(s).getCourses()) {
					Element course = new Element("课程");
					course.setAttribute("课程名", c.getCourseName());
					course.setText(c.getScore()+" ");
					student.addContent(course);
				}
			}
			students.addContent(student);
		}
		Format format = Format.getPrettyFormat();
		format.setEncoding("utf-8");
		format.setIndent("     ");
		XMLOutputter out = new XMLOutputter(format);
		try {
			out.output(doc,new FileOutputStream(filename));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	
	


	public static void main(String[] args) {
		ArrayList<String> list = readFile("H:\\score.txt");
		Map<String,Student> map = new TreeMap<>(new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o2.compareTo(o1);
			}
		});
		
		for(int i=0;i<list.size();i++) {
			String s = list.get(i);
			String info[] = s.split(",");
			if(!map.containsKey(info[0])) {
				Student student = new Student(info[0],info[1],new ArrayList<Course>());
				student.getCourses().add(new Course(info[2],Integer.parseInt(info[3])));
				map.put(info[0], student);
			}
			else {
				Student student = map.get(info[0]);
				student.getCourses().add(new Course(info[2],Integer.parseInt(info[3])));
			}
			
		}
		WriteFile(map,"H:\\output.xml");

	}

}