A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 孙胜 中级黑马   /  2013-6-4 14:51  /  1597 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

文件一共有2个,一个接口,一个实现,定义接口是为了以后用其他任意数据库或者其他方法都不用修改其他代码,只要重新设计实现类就Ok了
程序使用了DOM4j BeanUtils Logging 三个第三方jar包

还没有学数据库的平时想做一些数据的CURD可以用这个临时代替一下.
  1. package com.sunsheng.dao.inter;

  2. import java.io.IOException;
  3. import java.lang.reflect.InvocationTargetException;
  4. import java.util.List;

  5. import com.sunsheng.Exception.IdNotFoundException;

  6. public interface CURD {
  7.         /**
  8.          * 把javabean写入到xml文件中
  9.          * @param record
  10.          * @throws IOException
  11.          * @throws IllegalAccessException
  12.          * @throws InvocationTargetException
  13.          * @throws NoSuchMethodException
  14.          */
  15.         void create(Object record) throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException;
  16.        
  17.        
  18.         /**
  19.          * 根据指定的id修改xml数据
  20.          * @param id
  21.          * @param record
  22.          * @throws IOException
  23.          * @throws IllegalAccessException
  24.          * @throws InvocationTargetException
  25.          * @throws NoSuchMethodException
  26.          */
  27.         void update(int id, Object record)
  28.                         throws IOException,
  29.                         IllegalAccessException,
  30.                         InvocationTargetException,
  31.                         NoSuchMethodException;
  32.        
  33.        
  34.         /**
  35.          * 获得所有的xml元素
  36.          * @return 返回值是所有bean的list集合
  37.          * @throws IllegalAccessException
  38.          * @throws InvocationTargetException
  39.          * @throws InstantiationException
  40.          */
  41.         List read()
  42.                         throws IllegalAccessException,
  43.                         InvocationTargetException, InstantiationException;
  44.        
  45.        
  46.         /**
  47.          * 删除指定id的元素
  48.          * @param id
  49.          * @throws IdNotFoundException
  50.          * @throws IOException
  51.          */
  52.         void delete(int id)
  53.                         throws IdNotFoundException,
  54.                         IOException;

  55. }
复制代码
  1. package com.sunsheng.dao.imp;

  2. import java.beans.PropertyDescriptor;
  3. import java.io.*;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.util.ArrayList;
  6. import java.util.Iterator;
  7. import java.util.List;

  8. import org.apache.commons.beanutils.BeanUtils;
  9. import org.apache.commons.beanutils.PropertyUtils;
  10. import org.dom4j.*;
  11. import org.dom4j.io.*;

  12. import com.sunsheng.Exception.IdNotFoundException;
  13. import com.sunsheng.dao.inter.CURD;
  14. import com.sunsheng.domain.Person;

  15. public class XMLImp implements CURD {
  16.         private Document document;
  17.         private Class clazz;

  18.         private static XMLImp instance = new XMLImp();

  19.         private XMLImp() {
  20.                 super();
  21.         }

  22.         public static XMLImp getInstance() {
  23.                 return instance;
  24.         }

  25.        
  26.         /**
  27.          * 初始化document对象,如果xml不存在,会自动创建一个,根节点默认是records
  28.          * @param clazz 要转换成xml文件的bean的Class
  29.          * @throws DocumentException
  30.          * @throws IOException
  31.          */
  32.         public void init(Class clazz) throws DocumentException, IOException {
  33.                 init(clazz, "records");
  34.         }
  35.        
  36.        
  37.         /**
  38.          *
  39.          * @param clazz
  40.          * @param root 手动设置根节点的名字
  41.          * @throws DocumentException
  42.          * @throws IOException
  43.          */
  44.        
  45.         public void init(Class clazz, String root) throws DocumentException, IOException {
  46.                 this.clazz = clazz;
  47.                 SAXReader reader = new SAXReader();
  48.                 File file = new File("abc.xml");
  49.                
  50.                 //判断文件是否存在
  51.                 if (!file.exists()) {
  52.                         //不存在的话,创建一个空文件,留给xml2File方法使用
  53.                         file.createNewFile();
  54.                        
  55.                         //创建一个document对象,往这个对象里面添加一个根元素.
  56.                         document = DocumentHelper.createDocument();
  57.                         document.addElement(root);
  58.                 } else
  59.                         //存在就直接读文件
  60.                         document = reader.read(file);

  61.         }

  62.         @Override
  63.         public void create(Object record) throws IOException,
  64.                         IllegalAccessException, InvocationTargetException,
  65.                         NoSuchMethodException {

  66.                 // 获得xml文件的根节点
  67.                 Element root = document.getRootElement();

  68.                 // 根据record得到标签的名字
  69.                 String tagName = getTagName();

  70.                 // 得到record的id属性
  71.                 String value = (BeanUtils.getProperty(record, "id"));

  72.                 // 创建一个element,并添加到root下面,设置一个属性id
  73.                 Element element = root.addElement(tagName).addAttribute("id", value);

  74.                 // 在element下面创建多个子元素用来保存record的每一个属性
  75.                 PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(record);
  76.                 for (PropertyDescriptor pd : pds) {

  77.                         // 得到属性名,作为子标签名字.
  78.                         String childTagname = pd.getName();

  79.                         // 继承自Object类的class属性不存到xml中
  80.                         if ("class".equals(childTagname))
  81.                                 continue;

  82.                         // 得到该属性get方法返回值作为标签的text属性
  83.                         String childTagValue = pd.getReadMethod().invoke(record, null)
  84.                                         .toString();

  85.                         // 用得到的属性名和值添加一个子元素
  86.                         element.addElement(childTagname).addText(childTagValue);
  87.                 }

  88.                 // 保存xml到文件中
  89.                 xml2File();

  90.         }

  91.         @Override
  92.         public void update(int id, Object record) throws IOException,
  93.                         IllegalAccessException, InvocationTargetException,
  94.                         NoSuchMethodException {
  95.                 Person person = (Person) record;

  96.                 Element element = (Element) document.selectSingleNode("//person[@id="
  97.                                 + id + "]");

  98.                 for (Iterator iterator = element.elementIterator(); iterator.hasNext();) {
  99.                         Element e = (Element) iterator.next();
  100.                         // 获得标签的名字
  101.                         String name = e.getName();

  102.                         // 通过标签名字得到bean的属性值
  103.                         String text = BeanUtils.getProperty(person, name);

  104.                         // 修改标签的text值
  105.                         e.setText(text);

  106.                 }

  107.                 xml2File();
  108.         }

  109.         @Override
  110.         public List read() throws IllegalAccessException,
  111.                         InvocationTargetException, InstantiationException {
  112.                 List beans = new ArrayList();

  113.                 List list = document.selectNodes("//" + getTagName());
  114.                 // System.out.println(list);
  115.                 for (Iterator iterator = list.iterator(); iterator.hasNext();) {
  116.                         Object bean = clazz.newInstance();

  117.                         Element e = (Element) iterator.next();
  118.                         // 得到元素的所有属性对象
  119.                         List<Attribute> atts = e.attributes();
  120.                         for (Attribute att : atts) {
  121.                                 // 遍历每一个属性,按属性名和值设置到对应的bean中
  122.                                 BeanUtils.setProperty(bean, att.getName(), att.getValue());

  123.                         }
  124.                         Iterator it = e.elementIterator();
  125.                         while (it.hasNext()) {
  126.                                 Element value = (Element) it.next();
  127.                                 BeanUtils.setProperty(bean, value.getName(), value.getText());
  128.                         }
  129.                         beans.add(bean);

  130.                 }

  131.                 return beans;
  132.         }

  133.         @Override
  134.         public void delete(int id) throws IdNotFoundException, IOException {
  135.                 // 获得xml文件的根节点
  136.                 Node node = document.selectSingleNode("//" + getTagName() + "[@id="
  137.                                 + id + "]");
  138.                 if (node != null) {
  139.                         node.detach();
  140.                         xml2File();
  141.                 } else {

  142.                         throw new IdNotFoundException("您要删除的ID不存在");

  143.                 }
  144.         }

  145.         private void xml2File() throws IOException {
  146.                 OutputFormat format = OutputFormat.createPrettyPrint();
  147.                 XMLWriter writer;
  148.                 writer = new XMLWriter(new FileWriter("abc.xml"), format);
  149.                 writer.write(document);
  150.                 writer.close();

  151.         }

  152.         private String getTagName() {
  153.                 String beanName = clazz.getName();
  154.                 String tagName = beanName.substring(beanName.lastIndexOf(".") + 1)
  155.                                 .toLowerCase();
  156.                 return tagName;
  157.         }

  158. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
Sword + 1 赞一个!

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马