爪哇国新游记之十三----XML文件读写

/**
 * XML读写示例
 * @author hx
 *
 */
public class XmlReaderWriter{
    /**
     * 读取一个XML文件,返回一个雇员链表
     * @param fileName
     * @return
     */
    public List<Employee> readXml(String fileName){
        List<Employee> employees=new ArrayList<Employee>();

        SAXReader reader = new SAXReader();
        try {
            Document  document = reader.read(new File(fileName));
            Element root = document.getRootElement();

            List nodes = root.elements("employee");

            for (Iterator it = nodes.iterator(); it.hasNext();) {
                Employee employee=new Employee();

                // 根节点下的雇员子节点
                Element employeeElm = (Element) it.next();

                // 获取雇员子节点的id属性
                Attribute attribute=employeeElm.attribute("id");
                employee.setId(Long.parseLong(attribute.getText()));// 将文本形式的long字符串还原成基本类型

                // 获得雇员子节点的名称子节点
                Element nameElm=employeeElm.element("name");
                employee.setName(nameElm.getText());// 获取名称子节点的文字

                // 获取雇员子节点的性别子节点的文字
                employee.setMale(Boolean.parseBoolean(employeeElm.element("ismale").getText()));

                // 将雇员信息放入链表
                employees.add(employee);
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return employees;
    }

    /**
     * 将一个雇员链表写入XML文档
     * @param employees
     * @param fileName
     */
    public void writerToFile(List<Employee> employees,String fileName){
        // 创建文档对象
        Document document = DocumentHelper.createDocument();
        // 创建根节点
        Element root = document.addElement("employees");

        for(Employee emp:employees){
            // 创建employee节点
            Element empElm = root.addElement("employee");

            // 创建employee节点的id属性
            empElm.addAttribute("id", String.valueOf(emp.getId()));

            // 创建employee节点的子节点name
            Element nameElm = empElm.addElement("name");
            nameElm.setText(emp.getName());// 设置子节点的文字

            // 创建employee节点的子节点ismale
            Element ismaleElm = empElm.addElement("ismale");
            ismaleElm.setText(String.valueOf(emp.isMale()));// 设置子节点的文字
        }

        // 将document文档对象写入文件
        XMLWriter writer;
        try {
            writer = new XMLWriter(new FileWriter(fileName));
            writer.write(document);
            writer.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
    List<Employee> employees=new ArrayList<Employee>();
        /*employees.add(new Employee(1,"Andy",true));
        employees.add(new Employee(2,"Bill",false));
        employees.add(new Employee(3,"Cindy",true));
        employees.add(new Employee(4,"Doutglas",false));

        XmlReaderWriter xmlReaderWriter=new XmlReaderWriter();
        xmlReaderWriter.writerToFile(employees, "Employees20140724.xml");*/

        XmlReaderWriter xmlReaderWriter=new XmlReaderWriter();
        List<Employee> employee=xmlReaderWriter.readXml("Employees20140724.xml");
        employee=null;

    }
}
public class Employee{
    private long id;
    private String name;
    private boolean isMale;

    public Employee(){

    }

    public Employee(long id,String name,boolean isMale){
        this.id=id;
        this.name=name;
        this.isMale=isMale;
    }

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public boolean isMale() {
        return isMale;
    }
    public void setMale(boolean isMale) {
        this.isMale = isMale;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

这个的主要目的是让学生掌握如何导入第三方包。

爪哇国新游记之十三----XML文件读写

时间: 2024-12-28 21:26:08

爪哇国新游记之十三----XML文件读写的相关文章

爪哇国新游记之三十三----目录文件操作

1.判断路径是文件还是目录 File subDir=new File("c:\\mp3"); if(subDir.isDirectory()){ // 是目录 } File mp3=new File("c:\\mp3\\avemaria.mp3"); if(mp3.isFile()){ // 是文件 } 2.列出目录下的文件和子目录 File dir = new File(fromDir); String[] children = dir.list(); for (

爪哇国新游记之二十八----从url指定的地址下载一个文件到本地

package download; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.zip.GZIPInputStream; /** * 从url指定的地址下载一个文件到本地 * 2014

爪哇国新游记之十八----泛型栈类

import java.lang.reflect.Array; /** * 泛型栈 * * @param <T> */ public class Stack<T>{ private Class<T> type;// 栈元素所属的类 private int size;// 栈深度 private T[] arr;// 用数组存储 private int top;// 栈顶元素的下标 public Stack(Class<T> type,int size){ t

爪哇国新游记之二十二----算术表达式计算求值

代码: import java.util.ArrayList; import java.util.List; // 辅助类 class Item{ String value; boolean isNumber; public Item(String value,boolean isNumber){ this.value=value; this.isNumber=isNumber; } public Item(char c,boolean isNumber){ this.value=String.

爪哇国新游记之十九----使用Stack检查数字表达式中括号的匹配性

/** * 辅助类 * 用于记载字符和位置 * */ class CharPos{ char c; int pos; public CharPos(char c,int pos){ this.c=c; this.pos=pos; } } /** * 括号检查类 * */ public class BracketChecker{ /** * 检查函数 * @param str * @return * @throws Exception */ public static boolean check(

爪哇国新游记之十六----泛型单链表类

/** * 单链表节点类 * @param <T> */ class Node<T extends Object>{ protected T value; protected Node next; } /** * 单链表类 * @param <T> */ public class ChainList<T extends Object>{ private Node<T> first; public void addTail(T t){ Node&l

爪哇国新游记之十四----初试JDBC

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class A{ public static void search1(){ Connection conn=null; PreparedStatement ps=null; Resu

爪哇国新游记之十五----泛型动态数组类

import java.lang.reflect.Array; /** * 泛型动态数组类 * */ public class DynamicArray<T extends Object>{ private T[] arr; private Class<T> type; private int currCount; private static final int InitSize=2; public DynamicArray(Class<T> type){ this.

爪哇国新游记之十----异常初相识

import java.util.ArrayList; import java.util.List; public class A{ private int[] arr=new int[3]; private List<String> ls; public A(){ ls=new ArrayList<String>(); ls.add("12"); } public int getArrValue(int i){ return arr[i]; } public