JDOM 增删改查

package com.jscn.jsmack.utils;

import com.jscn.jsmack.vo.Task;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
/**
 * Created with IntelliJ IDEA.
 * User: wangy
 * Date: 15-3-30
 * Time: 上午11:38
 * To change this template use File | Settings | File Templates.
 */
public class JdomUtils {
    public static void main(String[] args) {
        String id = String.valueOf(new Random().nextInt(100));
        String senTime = "3";
        String money = "3";
        //文件路径
        String file = "c://task.xml";
        //文件编码
        String encoding = "utf-8";
        //appendElement(file, id, senTime, money, encoding);

        /*readXML(file);

        Task task = new Task();
        task.setStep(new String[]{"down"});
        task.setId(new String[]{"76"});
        task.setTimes(new String[]{"4"});
        updateXML(file, task);*/

        removeXML(file,"62");
    }

    public static void appendElement(String file, String id, String senTime, String money, String encoding) {
        Document doc;
        //利用SAX建立Document
        SAXBuilder bSAX = new SAXBuilder(false);
        try {
            //生成document对象
            doc = bSAX.build(new File(file));//"c://task.xml"
            Element root = doc.getRootElement();

            Element card = appendCard(id, senTime, money);

            root.addContent(card);

            XMLOutputter outputter = new XMLOutputter();
            Format format = Format.getPrettyFormat();

            format.setEncoding(encoding);
            outputter.setFormat(format);

            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), encoding);
            outputter.output(doc, out);

            if (out != null)
                out.close();

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

    //增加task元素
    public static Element appendCard(String id, String time, String step) {
        Element card = new Element("task");
        card.setAttribute("id", id);

        Element moneyElem = new Element("step");
        moneyElem.setText(step);

        Element senTimeElem = new Element("time");
        senTimeElem.setText(time);

        card.addContent(senTimeElem);
        card.addContent(moneyElem);

        return card;
    }

    public static void saveXML(Document doc, String file) {
        // 将doc对象输出到文件
        try {
            // 创建xml文件输出流
            XMLOutputter xmlopt = new XMLOutputter();

            // 创建文件输出流
            FileWriter writer = new FileWriter(file);
            // 指定文档格式
            Format fm = Format.getPrettyFormat();
            // fm.setEncoding("GB2312");
            xmlopt.setFormat(fm);
            // 将doc写入到指定的文件中
            xmlopt.output(doc, writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取XML
    public static List<Task> readXML(String file) {
        SAXBuilder sb = new SAXBuilder();
        Document doc = null;
        List<Task> taskList = new ArrayList<Task>();
        Task task = null;
        try {
            doc = sb.build(file);
            Element root = doc.getRootElement();
            List<Element> list = root.getChildren("task");
            if (list != null && list.size() > 0) {
                for (Element el : list) {
                    task = new Task();
                    String id = el.getAttributeValue("id");
                    String step = el.getChildText("step");
                    String time = el.getChildText("time");
                    task.setId(new String[]{id});
                    task.setStep(new String[]{step});
                    task.setTimes(new String[]{time});
                    taskList.add(task);
                    System.out.println(id);
                    System.out.println(step);
                    System.out.println(time);
                }
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return taskList;
    }
    public static Task readXMLById(String file,String id) {
        SAXBuilder sb = new SAXBuilder();
        Document doc = null;
        Task task = null;
        try {
            doc = sb.build(file);
            Element root = doc.getRootElement();
            List<Element> list = root.getChildren("task");
            if (list != null && list.size() > 0) {
                for (Element el : list) {
                    if(el.getAttributeValue("id").equals(id)){
                        task = new Task();
                        task.setId(new String[]{id});
                        task.setStep(new String[]{el.getChildText("step")});
                        task.setTimes(new String[]{el.getChildText("time")});
                        break;
                    }
                }
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return task;
    }
    //根据task节点 更新XML
    public static void updateXML(String file, Task task) {
        SAXBuilder sb = new SAXBuilder();
        Document doc = null;
        try {
            doc = sb.build(file);
            Element root = doc.getRootElement();
            List<Element> list = root.getChildren("task");
            for (Element el : list) {
                if (el.getAttributeValue("id").equals(task.getId()[0])) {
                    Element step = el.getChild("step");
                    step.setText(task.getStep()[0]);
                    Element time = el.getChild("time");
                    time.setText(task.getTimes()[0]);
                    break;
                }
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        saveXML(doc, file);
    }
    //根据task 属性ID 删除节点task
    public static void removeXML(String file, String id) {
        SAXBuilder sb = new SAXBuilder();
        Document doc = null;
        try {
            doc = sb.build(file);
            Element root = doc.getRootElement();
            List<Element> list = root.getChildren("task");
            for (Element el : list) {
                if (el.getAttributeValue("id").equals(id)) {
                    root.removeContent(el);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        saveXML(doc, file);
    }

    //用UUID来作为task的ID
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replaceAll("-{1}", "");
    }
}

你可能感兴趣的:(jdom)